標籤:abc 列表 ted condition sequence 就會 元組 刪除 cond
一.賦值
#序列解包>>> x,y,z = 1,2,3>>> print(x,y,z)1 2 3>>> dic = {‘Jameson‘:‘1001‘,‘Jack‘:‘1002‘,‘Abel‘:‘1003‘}>>> key,val = dic.popitem()>>> print(key,val)Jack 1002#鏈式賦值>>> a = b = c = 3>>> print(a,b,c)3 3 3#增量賦值>>> str2 = "abc">>> str2 += "def">>> str2‘abcdef‘>>> str2 *= 3>>> str2‘abcdefabcdefabcdef‘ 二.條件陳述式和其他
#if,elif,elseif condition_1: statement_block_1elif condition_2: statement_block_2else: statement_block_3#比較子"""x == y x等於yx < y x小於yx > y x大於yx >= y x大於等於yx <= y x小於等於yx != y x不等於yx is y x和y是同一個 對象x is not y x和y是不同 對象x in y x是y容器(例如,序列) 的成員x not in y x不是y容器(例如,序列) 的成員"""#布林運算子 (貌似python中沒有 || && !)and or not#斷言(不解釋)assert
三.迴圈和其他
#whilex = 1while x < 4: print(x) x += 1輸出:123count = 0while count < 5: print (count, " 小於 5") count = count + 1else: print (count, " 大於或等於 5")輸出:0 小於 51 小於 52 小於 53 小於 54 小於 55 大於或等於 5#forfor <variable> in <sequence>: <statements>else: <statements>##例子:for number in range(1,101):#列印1~100 print(number)dic = {‘x‘:‘1‘,‘y‘:‘2‘,‘z‘:‘3‘}for key in dic: print(key + ":",dic.get(key))輸出:x: 1z: 3y: 2dic = {‘x‘:‘1‘,‘y‘:‘2‘,‘z‘:‘3‘}for key,val in dic.items(): print(key + ":",val)輸出:z: 3y: 2x: 1#break,continue 略#pass pass是空語句,是為了保持程式結構的完整性。#迭代工具##zip (zip可以處理不等長序列,最短的序列“用完”的時候就會停止)>>> a = ["x","y","z"]>>> b = ["1","2","3"]>>> list(zip(a,b))[(‘x‘, ‘1‘), (‘y‘, ‘2‘), (‘z‘, ‘3‘)]#加入迴圈a = ["x","y","z"]b = ["1","2","3","4"]for letter,num in zip(a,b): print(letter,num)輸出:x 1y 2z 3##enumerate 對一個可遍曆的資料對象(如列表、元組或字串),enumerate會將該資料對象組合為一個索引序列,同時列出資料和資料下標(好繞,明白就行)a = ["x","y","z"]for i,letter in enumerate(a): print(i,a[i])輸出:0 x1 y2 z#reversed和sorted 翻轉和排序迭代>>> sorted("Hello,woeld!")[‘!‘, ‘,‘, ‘H‘, ‘d‘, ‘e‘, ‘e‘, ‘l‘, ‘l‘, ‘l‘, ‘o‘, ‘o‘, ‘w‘]>>> list(reversed("Hello,woeld!"))[‘!‘, ‘d‘, ‘l‘, ‘e‘, ‘o‘, ‘w‘, ‘,‘, ‘o‘, ‘l‘, ‘l‘, ‘e‘, ‘H‘]##while True 略
四.列表推導式和pass、del、exec
#列表推導式是利用其他列表建立新列表的一種方法>>> [x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> [x*x for x in range(10) if x % 3 == 0][0, 9, 36, 81]>>> [x+1 for x in range(10)][1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> [(x,y) for x in range(3) for y in range(3)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]還可以>>> girls = [‘alice‘,‘bernice‘,‘clarice‘]>>> boys = [‘charis‘,‘arnold‘,‘bob‘]>>> letterGirls = {}>>> for girl in girls: letterGirls.setdefault(girl[0],[]).append(girl)#還可以這麼用,我服,查了下setdefault(key[, default])如果key在字典中,則返回其值。如果沒有,則插入值為default的key,並返回default。原來返回了列表,難怪能append!>>> letterGirls{‘c‘: [‘clarice‘], ‘b‘: [‘bernice‘], ‘a‘: [‘alice‘]}>>> print([b+"+"+g for b in boys for g in letterGirls[b[0]]])[‘charis+clarice‘, ‘arnold+alice‘, ‘bob+bernice‘]
#pass pass是空語句,是為了保持程式結構的完整性。#del刪除變數#exec和eval回頭再研究吧
參考《Python基礎教程》(第2版)·修訂版
Python基本文法