Python 開發中有哪些高級技巧?這是知乎上一個問題,我總結了一些常見的技巧在這里,可能談不上多高級,但掌握這些至少可以讓你的代碼看起來 Pythonic 一點。如果你還在按照類C語言的那套風格來寫的話,在 code review 恐怕會要被吐槽了。
列表推導式
>>> chars = [ c for c in 'python' ]>>> chars['p', 'y', 't', 'h', 'o', 'n']
字典推導式
>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}>>> double_dict1 = {k:v*2 for (k,v) in dict1.items()}>>> double_dict1{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}
集合推導式
>>> set1 = {1,2,3,4}>>> double_set = {i*2 for i in set1}>>> double_set{8, 2, 4, 6}
合并字典
>>> x = {'a':1,'b':2}>>> y = {'c':3, 'd':4}>>> z = {**x, **y}>>> z{'a': 1, 'b': 2, 'c': 3, 'd': 4}
復制列表
>>> nums = [1,2,3]>>> nums[::][1, 2, 3]>>> copy_nums = nums[::]>>> copy_nums[1, 2, 3]
反轉列表
>>> reverse_nums = nums[::-1]>>> reverse_nums[3, 2, 1] PACKING / UNPACKING
變量交換
>>> a,b = 1, 2>>> a ,b = b,a>>> a2>>> b1
高級拆包
>>> a, *b = 1,2,3>>> a1>>> b[2, 3]
或者
>>> a, *b, c = 1,2,3,4,5>>> a1>>> b[2, 3, 4]>>> c5
函數返回多個值(其實是自動packing成元組)然后unpacking賦值給4個變量
>>> def f():... return 1, 2, 3, 4...>>> a, b, c, d = f()>>> a1>>> d4
列表合并成字符串
>>> " ".join(["I", "Love", "Python"])'I Love Python'
鏈式比較
>>> if a > 2 and a < 5:... pass...>>> if 2<a<5:... passyield from# 沒有使用 field fromdef dup(n): for i in range(n): yield i yield i# 使用yield fromdef dup(n): for i in range(n): yield from [i, i]for i in dup(3): print(i)>>>001122
in 代替 or
>>> if x == 1 or x == 2 or x == 3:... pass...>>> if x in (1,2,3):... pass
字典代替多個if else
def fun(x): if x == 'a': return 1 elif x == 'b': return 2 else: return Nonedef fun(x): return {"a": 1, "b": 2}.get(x)
有下標索引的枚舉
>>> for i, e in enumerate(["a","b","c"]):... print(i, e)...0 a1 b2 c
生成器
新聞熱點
疑難解答