大家請注意:這篇文中假設我們都用的是Python 3
1. 列表推導式
你有一個list:bag = [1, 2, 3, 4, 5]
現在你想讓所有元素翻倍,讓它看起來是這個樣子: [2, 4, 6, 8, 10]
大多是初學者,根據之前語言的經驗會大概這樣來做
bag = [1, 2, 3, 4, 5] for i in range(len(bag)): bag[i] = bag[i] * 2
但是有更好的方法:
bag = [elem * 2 for elem in bag]
很簡潔對不對?這叫做Python的列表推導式。
2. 遍歷列表
繼續,還是上面的列表。
如果可能盡量避免這樣做:
bag = [1, 2, 3, 4, 5] for i in range(len(bag)): print(bag[i])
# 取而代之的應該是這樣:
##
bag = [1, 2, 3, 4, 5] for i in bag: print(i)
bag = [1, 2, 3, 4, 5] for index, element in enumerate(bag): print(index, element)
a = 5 b = 10 # 交换 a 和 b tmp = a a = b b = tmp
但Python提供了一個更自然更好的方法!
a = 5 b = 10 # 交换a 和 b a, b = b, a
夠漂亮吧?
4. 初始化列表
假如你想要一個是10個整數0的列表,你可能會先想到:
bag = [] for _ in range(10): bag.append(0)
#換個方式吧:
bag = [0] * 10
看,多優雅。
注意:如果你列表包含了列表,這樣做會產生淺拷貝。
舉例:
bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]]
Oops!所有的清單都改變了,而我們只是想要改變第一個清單。
改一改啦:
bag_of_bags = [[0] for _ in range(5)] # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [0], [0], [0], [0]]
問問自己,初始化一個清單是必須的嗎?
name = "Raymond" age = 22 born_in = "Oakland, CA" string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "." print(string)
name = "Raymond" age = 22 born_in = "Oakland, CA" string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in) print(string)
def binary(): return 0, 1 result = binary() zero = result[0] one = result[1]
def binary(): return 0, 1 zero, one = binary()
zero, _ = binary()
##就是這麼高效率!
7. 存取Dicts(字典)
你也會經常在dicts中寫入key,pair(鍵,值)。
如果你試圖存取一個不存在的於dict的key,可能會為了避免KeyError錯誤,你會傾向於這樣做:
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr[i] += 1 else: countr[i] = 1 for i in range(10): if i in countr: print("Count of {}: {}".format(i, countr[i])) else: print("Count of {}: {}".format(i, 0))
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr[i] = countr.get(i, 0) + 1 for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = dict([(num, bag.count(num)) for num in bag]) for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))
countr = {num: bag.count(num) for num in bag}
from collections import Counter bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = Counter(bag) for i in range(10): print("Count of {}: {}".format(i, countr[i]))
2、它們的演算法可能會是最優的,這樣就跑的速度會更快。
3、抽象化:它們指向明確且文檔友好,你可以專注於那些還沒有被實現的。
4、最後,它都已經在那裡了,你不用再造輪子了。
9. 在清單中切片/步進
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[:5]: print(elem)
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[-5:]: print(elem)
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for index, elem in enumerate(bag): if index % 2 == 0: print(elem)
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[::2]: print(elem) # 或者用 ranges bag = list(range(0,10,2)) print(bag)
你也可以在寫程式碼時用空格來定義tab。這樣你可以自己選擇用幾個空格當tab。大多數Python用戶是用4個空格。
總結
以上就是為大家總結的Python開發中要注意的小貼士,希望對大家學習和使用python能有所幫助,如果有疑問可以留言交流。
更多Python開發中要注意的相關文章請關注PHP中文網!