1. 程式人生 > >Python入門學習筆記_1

Python入門學習筆記_1

基礎一

賦值

a = b = c = d = 10

e記法

a = 0.000000025
b = 2.5e-8
print(a, "\n")
print(b)

變數型別轉換

a = "520"
b = int(a)
b
a = 5.99
b = int(a)
b
a = "520"
b = float(a)
b
b = str(5e+19)
b
a = "520"
type(a)
a = "打野"
isinstance(a, str)

運算子

+, -, *, /, %, **, //
#//地板除,取商
print(10 // 4)
print(3.0 // 2)
#冪運算
print(3 ** 3)
# 同時得到商和餘數
print(divmod(9, 5))
2
1.0
27
(1, 4)

邏輯操作符

True and False
True or False
not True
3 < 4 < 5

條件分支

a = 0
if True:
    a = 1;
else:
    a = 2;
a

while迴圈

a = 0
while a < 8:
    a += 1

輸入

temp = input("Enter a number:")
print(temp)

匯入包

import keyword
print( keyword.kwlist )

斷言(assert)

assert
3 < 4

for迴圈

str = "Daye"
for ch in str:
    print(ch, end = " ")
member = ["Tom", "Nancy", "Tom", "Bill"]
for each in member:
    print(each, len(each))
range(5)
list(range(5)) 
for each in range(2, 9):
    print(each)
for each in range(1, 10, 2):
    print(each)

基礎二

字串

  1. 分片([start : end : step])
str = 'Daye is a boy'
print(str[ : 13 : 2])
print(str[-3 :  : 1]) #倒數第三位到最後一位
Dy saby
boy
  1. split()分割
str2 = 'I am twenty-two years old'
print(str2.split())

str3 = 'apple,pear,banana,bean'
print(str3.split(','))
['I', 'am', 'twenty-two', 'years', 'old']
['apple', 'pear', 'banana', 'bean']
  1. join()合併
crypto_list = ['yellow', 'blue', 'black', 'white']
crypto_string = ','.join(crypto_list)
print(crypto_string)
yellow,blue,black,white
  1. startswith()、endswith()
poem = 'All that doth flow we cannot liquid name that'
print("startswith = ", poem.startswith('All'))
print("endswith = ", poem.endswith('name'))
startswith =  True
endswith =  False
  1. find()、rfind()
print(poem.find('that'))
print(poem.rfind('that'))#最後一次出現的位置
4
41
  1. count()
poem.count('that')
2
  1. isalnum()是否全為數字或者字母
print("pome ", poem.isalnum())
poem2 = 'abcd'
print("pome2 ", poem2.isalnum())
pome  False
pome2  True
  1. strip()將字串尾部的規定字元刪除
setup = 'a duck goes into a bar...'
setup.strip('.')
'a duck goes into a bar'
  1. 大小寫操作
  • capitalize()[將字串首字母大寫]
setup.capitalize()
'A duck goes into a bar...'
  • title()[將所有單詞的開頭字母大寫]
setup.title()
'A Duck Goes Into A Bar...'
  • upper()[將所有字母變成大寫]
setup.upper()
'A DUCK GOES INTO A BAR...'
  • lower()[將所有字母變成小寫]
setup.lower()
'a duck goes into a bar...'
  • swapcase()[將所有字母大小寫轉換]
setup.swapcase()
'A DUCK GOES INTO A BAR...'
  1. 格式排版函式
  • center()、ljust()、rjust()
print(setup.center(30))
print(setup.ljust(30))
print(setup.rjust(30))
  a duck goes into a bar...   
a duck goes into a bar...     
     a duck goes into a bar...
  1. replace()
setup.replace('duck', 'marmoset', 100)#100表示最多修改次數
'a marmoset goes into a bar...'

列表、元組、字典與集合

列表

  1. 普通列表
member = ["Tom", "Nancy", "Tony", "Bill"]
print(member)
number = [1, 2, 3, 4, 5]
print(number)
['Tom', 'Nancy', 'Tony', 'Bill']
[1, 2, 3, 4, 5]
  1. 混合列表
mex = [1, "Daye", 3.14, [1, 2, 3]]
print(mex)
  1. 空列表
empty = []
empty

向列表新增元素

  1. append()方法
member.append("Linda")
member
  1. extend()方法
member.extend(['Dear', 'Pmr'])
member
  1. insert()方法
member.insert(1, 'Zqy')
member

從列表中刪除元素

  1. remove()方法
member.remove('Tom')
member
  1. del方法
del member[0] #如果不加下標,會整個列表刪除
member
['Nancy', 'Bill', 'Linda', 'Dear', 'Pmr']
  1. pop()方法[有返回值]
member.pop()
'Pmr'
name = member.pop()
name
'Dear'
member.pop(1)
member
['Nancy', 'Linda']

列表分片(Slice)

print("member = ", member)
print("1:3 = ", member[1:3])
print(":3 = ", member[:3])
print(": = ", member[:])
print(": : 2= ", member[: : 2])
member =  ['Tom', 'Nancy', 'Tony', 'Bill']
1:3 =  ['Nancy', 'Tony']
:3 =  ['Tom', 'Nancy', 'Tony']
: =  ['Tom', 'Nancy', 'Tony', 'Bill']
: : 2=  ['Tom', 'Tony']

列表常用操作符

  1. 比較操作符
list1 = [123, 456]
list2 = [234, 123]
print("list1 > list2 = ", list1 > list2) #第一個決定大小,如果相等比較下一個,以此類推
list3 = [123, 456]
print("list1 < list2) and (list1 == list3) = ", (list1 < list2) and (list1 == list3))
list1 > list2 =  False
list1 < list2) and (list1 == list3) =  True
  1. 連線、重複操作符
#list4 = list1 + list2 建議不要使用,使用extend
list3 * 3
list3 *= 3
print(list3)
[123, 456, 123, 456, 123, 456]
  1. 成員關係操作符
123 in list3
"123" not in list3
True
list5 = [123, ["Daye", "Pmr"], 456]
print('Daye' in list5)
print('Daye' in list5[1])
print(list5[1][1])
False
True
Pmr
  1. 內建函式
print(dir(list))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  • count()
print(list3.count(123))
81
  • index(member, startSite, endSite)
print(list3)
print(list3.index(123, 3, 10)) #3-10內,123出現的位置
[123, 456, 123, 456, 123, 456]
4
  • reverse()
list3.reverse()
print(list3)
[456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123, 456, 123]
  • sort()
list6 = [4, 5, 6, 1, 10, 2]
list6.sort()
print(list6)
list6.sort(reverse = True)
print(list6)
list6_1 = sorted(list6)
print(list6_1)
[1, 2, 4, 5, 6, 10]
[10, 6, 5, 4, 2, 1]
[1, 2, 4, 5, 6, 10]
  • 分片拷貝**(注意)**
list7 = list6
print("list7 = ", list7)
list8 = list6[:]
print("list8 = ", list8)
list9 = list6.copy()
print("list9 = ", list9)
#list6.sort()
list6.sort()
print("反向排序後:")
print("list7 = ", list7)
print("list8 = ", list8)
print("list9 = ", list9)
list7 =  [10, 6, 5, 4, 2, 1]
list8 =  [10, 6, 5, 4, 2, 1]
list9 =  [10, 6, 5, 4, 2, 1]
反向排序後:
list7 =  [1, 2, 4, 5, 6, 10]
list8 =  [10, 6, 5, 4, 2, 1]
list9 =  [10, 6, 5, 4, 2, 1]
  • join()
marxes = ['yellow', 'black', 'white']
print(','.join(marxes))
yellow,black,white

元組

建立元組

  1. 普通建立
empty_tutle = ()
print(empty_tutle)
one_marx = 'Groucho',#如果裡面只有一個元素,需要在末尾加上','逗號
print(one_marx)
marx_tuple = ('yellow', 'black', 'white')
print(marx_tuple)
x, y, z = marx_tuple  #可直接將元組賦值給多個變數,變數數量 = 元組元素個數
print(x, " ", y, " ", z)
()
('Groucho',)
('yellow', 'black', 'white')
yellow   black   white
  1. 利用tuple()函式建立元組
marx_list = ['yellow', 'black', 'white'] #建立一個列表
tuple(marx_list)
('yellow', 'black', 'white')

字典

建立字典

  1. 普通建立
empty_dict = {}
print(empty_dict)
bierce = {
    "day" : "A period of twenty-four hours",
    "positive" : "Mistaken at the top of one's voice",
    "misfortune" : "The kind of fortune that never misses"
}
print(bierce)
{}
{'day': 'A period of twenty-four hours', 'positive': "Mistaken at the top of one's voice", 'misfortune': 'The kind of fortune that never misses'}
  1. 利用dict()函式轉換為字典
lol = [['a', 'b'], ['c', 'd'], ['e', 'f']]  #列表+子列表
print("列表+子列表: ", dict(lol))
lot = [('a', 'b'), ('c', 'd'), ('e', 'f')]  #列表+元組
print("列表+元組: ", dict(lot))
tol = (['a', 'b'], ['c', 'd'], ['e', 'f'])  #元組+列表
print("元組+列表: ", dict(tol))
los = ['ab', 'cd', 'ef']  #列表+雙字元
print("列表+雙字元: ", dict(los))
tos = ('ab', 'cd', 'ef')  #元組+雙字元
print("元組+雙字元: ", dict(tos))
列表+子列表:  {'a': 'b', 'c': 'd', 'e': 'f'}
列表+元組:  {'a': 'b', 'c': 'd', 'e': 'f'}
元組+列表:  {'a': 'b', 'c': 'd', 'e': 'f'}
列表+雙字元:  {'a': 'b', 'c': 'd', 'e': 'f'}
元組+雙字元:  {'a': 'b', 'c': 'd', 'e': 'f'}

使用[key]新增或修改元素

some_pythons = {
    'A':'Tony',
    'B':'Nancy',
    'C':'Tom',
    'D':'Linda',
    'E':'Terry'
}
print(some_pythons)
some_pythons['E'] = 'Anny'
some_pythons['F'] = 'Lucy'
print(some_pythons)
{'A': 'Tony', 'B': 'Nancy', 'C': 'Tom', 'D': 'Linda', 'E': 'Terry'}
{'A': 'Tony', 'B': 'Nancy', 'C': 'Tom', 'D': 'Linda', 'E': 'Anny', 'F': 'Lucy'}

update()合併字典

other = {'G':'Vance', 'H':'Case'}
some_pythons.update(other)
print(some_pythons)
{'A': 'Tony', 'B': 'Nancy', 'C': 'Tom', 'D': 'Linda', 'E': 'Anny', 'F': 'Lucy', 'G': 'Vance', 'H': 'Case'}

del刪除元素

del some_pythons['H']
some_pythons
{'A': 'Tony',
 'B': 'Nancy',
 'C': 'Tom',
 'D': 'Linda',
 'E': 'Anny',
 'F': 'Lucy',
 'G': 'Vance'}

clear()刪除所有元素

other.clear()
other
{}

獲取元素

print(some_pythons['A'])
print(some_pythons.get('B'))
Tony
Nancy
dict_keys(['A', 'B', 'C', 'D', 'E', 'F', 'G'])

獲取鍵和值

print(some_pythons.keys())  #取得鍵
print(some_pythons.values())  #取得值
print(some_pythons.items())  #取得鍵和值
dict_keys(['A', 'B', 'C', 'D', 'E', 'F', 'G'])
dict_values(['Tony', 'Nancy', 'Tom', 'Linda', 'Anny', 'Lucy', 'Vance'])
dict_items([('A', 'Tony'), ('B', 'Nancy'), ('C', 'Tom'), ('D', 'Linda'), ('E', 'Anny'), ('F', 'Lucy'), ('G', 'Vance')])

集合

建立集合

empty_set = set()
print(empty_set)
even_number = {0, 1, 3, 5, 7}
print(even_number)
print(set('letters'))  #值不可重複,同樣用列表、元組、字典都可以建立集合。需注意的是字典轉為集合,只有鍵
set()
{0, 1, 3, 5, 7}
{'l', 'r', 's', 'e', 't'}

合併及運算子

a = {1, 2}
b = {2, 3}
  • 交集(共有元素)
print("a & b = ", a & b)
print("intersection(): ", a.intersection(b))
a & b =  {2}
intersection():  {2}
  • 並集(合併但不重複)
print("a | b = ", a | b)
a | b =  {1, 2, 3}
  • 差集(出現在第一個單不出現在第二個)
print("a - b", a - b)
a - b {1}
  • 異或集(僅在兩個集合中出現一次)
print("a ^ b", a ^ b)
print("symmetric_difference(): ", a.symmetric_difference(b))
a ^ b {1, 3}
symmetric_difference():  {1, 3}
  • 判斷是否為子集
print("a <= b", a <= b)
print("issubset(): ", a.issubset(b))
a <= b False
issubset():  False
  • 判斷是否為真子集
print("a < b", a < b)
print("issuperset(): ", a.issuperset(b))
a < b False
issuperset():  False