Python基礎知識回顧(也可以說有點小技巧性的東西)
阿新 • • 發佈:2018-12-17
交換變數
a,b=2,3
a,b=b+1,a
print(a,b)
結果如下:
4 2
字典推導和集合推導
some_list=[1,2,3,4,5,6] another_list=[i+1 for i in some_list] #列表的推導 print(another_list) 結果如下: [2, 3, 4, 5, 6, 7] ------------------------------------------------------- even_set={x for x in some_list if x%2==0} #集合的推導 print(even_set) 結果如下: {2, 4, 6} ------------------------------------------------------- d={x:x%2==0 for x in range(1,11)} #字典的推導 print(d) 結果如下: {1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True} #注意上面的結果返回值 ------------------------------------------------------- som_list=["English","China","US","Japan"] mydict={key:value for key,value in enumerate(som_list)} #字典的推導 print(mydict) 結果如下: {0: 'English', 1: 'China', 2: 'US', 3: 'Japan'}
計數時使用Counter
from collections import Counter #需要從collections 模組中引入Counter c="hello world" c=Counter("hello world") #統計字串中各個字元出現的次數 print(c) print(type(c)) print(c.most_common(3)) 結果如下: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) <class 'collections.Counter'> [('l', 3), ('o', 2), ('h', 1)]
寫一個程式,列印數字1到100,3的倍數列印“Fizz”來替換這個數,5的倍數列印“Buzz”,對於既是3的倍數又是5的倍數的數字列印“FizzBuzz”。
for x in range(1,101):
print("fizz"[x % 3 * len('fizz')::] + "buzz"[x % 5 * len('buzz')::] or x)
#這裡用到了[start:end:len]操作,結果太長,自行測試
同時遍歷兩個序列
nfc=["hello","hi"] afc=["john","robot"] combine=zip(nfc,afc) for tema,temb in zip(nfc,afc): print(tema+":"+temb) for tema,temb in combine: #這個和上面那條語句效果一樣 print(tema+":"+temb) 結果如下: hello:john hi:robot hello:john hi:robot
用乘法初始化列表的值
items=["hello"]*3
items=[0]*3
print(items)
結果如下:
[0, 0, 0]
列表轉化為字串
teams=["Jordon","Micheal","Kebi"]
print(",".join(teams))
結果如下:
Jordon,Micheal,Kebi
-------------------------------------------
num=[i for i in range(5)]
print(",".join(num)) #join()只能作用於字串,這樣會出錯,自行測試
從字典中取元素
data={1:"Tech",2:"Py"}
#data[3]直接取字典中的關鍵字,可能由於關鍵字的不存在而導致出錯
#穩妥的方法使用try/except,儘管他不盡優雅
try:
temp=data[3]
except KeyError:
temp=False
----------------------------------------------------------
#優雅的取值方法
temp=data.get(3,None)
print(temp)
結果如下:
None
求一個序列所有組合的可能的種數
from itertools import combinations
teams=["hello","world","China","US"]
for combines in combinations(teams,3): #這個3只是一個引數,你輸入不大於列表長度的數均可
print(combines)
結果如下:
('hello', 'world', 'China')
('hello', 'world', 'US')
('hello', 'China', 'US')
('world', 'China', 'US')