此篇是作者(一個萌新)在學習Python3的一點回顧和總結(适合有java或c基礎的讀者觀看)
條件控制
- if 語句
- 基本
if True == 1: print("hehe")
- 雙向
if True == 2: print("hehe") else: print("haha")
- 多路
if True == 2: print("hehe") elif False == -1: print("haha") else: print("hoho")
- if 嵌套
if True == 2: print("hehe") if 1 > 2: print("gege") elif 2 > 3: print("gogo") else: print("gaga") elif False == -1: print("hoho") else: print("haha")
- 基本
循環語句
- for循環
for i in [1,2,3,4]:
print(i)
- range函數
for i in range(2,5,1):
print(i) # range()生成一個從2開始到5步長為1的一個算頭不算尾的數字序列
- break, continue, pass:前兩個與java中的一樣,pass表示略過,用于占位
x = ['tom', 'jack']
for i in x:
pass
print(i)
- while循環(在Python中不存在do……while)
n = 5
while n >0:
print(n)
n = n - 1
else:
print('n為零')
異常
- 正常異常處理
try:
number = int(input("請輸入一個數字"))
ret = 1/number
print("計算結果是:{0}".format(ret))
except:
print("輸入錯誤")
finally:
print("希望您每天開開心心")
- 使用者手動引發
try:
raise NameError # 産生異常,不會繼續往下運作
number = int(input("請輸入一個數字"))
ret = 1/number
print("計算結果是:{0}".format(ret))
except NameError as e:
print("NameError")
finally:
print("希望您每天開開心心")
疊代器和生成器
- 可疊代:可以用for循環周遊的對象,我們稱之為可疊代的對象
for i in "hasdjkhasjkhsjkshd":
print(i)
# 我們可以通過collections子產品的Iterable類型來驗證該對象是否可疊代
from collections import Iterable
print(isinstance('sdadasdsada', Iterable))
- 疊代器:
- iter()、next()
i = iter("dsajdkhjasjdh") n = 1 while n: try: print(next(i)) except StopIteration as e: n = 0
-
自定義疊代器
實作了__iter__()與__next__()這兩個方法的一個類
- iter():傳回一個特殊的疊代器對象
- next():傳回下一個疊代器對象
class OuShu: def __iter__(self): self.b =0 return self def __next__(self): x = self.b self.b += 2 return x myclass = OuShu() myiter = iter(myclass) mynext = next(myiter) while mynext < 10: mynext = next(myiter) print(mynext)
-
生成器
生成器是一個傳回疊代器的函數,生成器就是一個疊代器,使用了yield的函數被稱為生成器。
- yield:遇到yield時函數會暫停并儲存目前所有的運作資訊,傳回yield的值,并在下次運作next()方法時從目前位置繼續執行
# 斐波那契數列 def fbc(max): a, b, n = 0, 1, 0 while n < max: yield b a, b = b, a+b n += 1 max = int(input("您需要多少位斐波那契數")) f = fbc(max) for i in range(0,max): print(next(f))
- yield:遇到yield時函數會暫停并儲存目前所有的運作資訊,傳回yield的值,并在下次運作next()方法時從目前位置繼續執行
資料結構
- 清單
- 将清單當堆棧使用:用append()将一個元素添加堆棧頂部,用不指定索引pop()将一個元素從堆棧頂釋放
- 将清單當隊列使用:用append()往隊列尾添加元素,用popleft()将隊列頭删除
- 嵌套清單(多元數組):[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
方法 | 描述 |
---|---|
list.append(x) | 将x添加到清單末尾 |
list.extend(list) | 将一個清單添加在清單末尾,兩個清單的重複元素隻保留一個 |
list.insert(a, x) | 将x添加到a位置,其他元素依次後移 |
list.remove(x) | 隻将清單的第一個的元素删除 |
list.pop(a) | 将指定a位置的元素删除 |
list.index(x) | 傳回x在清單的位置 |
list.clear(list) | 将清單清空,但清單還存在 |
list.count(x) | 傳回清單内x元素的個數 |
list.sort(key=none, reverse=False) | 将清單的元素排序,key可以定義為一個函數,reverse有兩個選項False和True, False為從大到小,True為從小到大 |
list.reverse() | 反轉清單 |
list.copy() | 傳回這個清單的副本 |
- 元組(與list類似,但不可修改)
- 隻有三個方法
- len():傳回元祖長度
- 連接配接:
tuple0 = (1, 2, 3) tuple2 = (4, 5, 6) tuple3 = tuple0 + tuple2 print(tuple3)
- in 查詢:
print(1 in (1, 2, 3))
- 隻有三個方法
- 集合:可以用set()或大括号建立集合,如果建立空集合必須用set()
- 字典:用{}建立空字典,可以用{key: value, key: value}直接建立或者使用dict([key: value,……])
- 周遊
dicty = {'tom':1, 'jack':2, 'rose':3} # items得到關鍵字與對應的值 for k, v in dicty.items(): print(k, v) # enumerate得到索引位置和對應值 for i, v in enumerate(dicty): print(i, v)
- 添加、删除元素
d = {} # 添加,如果字典中存在key=a,那麼就會覆寫 d.update(a=2) # 也可以為update({'a': 2}) print(d) # 删除 d.pop('a') # pop()裡為key值
[如果讀者沒有看懂或者覺得我寫的不好可以看官方文檔,在此附上連結 ](https://docs.python.org/zh-cn/3/)