看板 Python 關於我們 聯絡資訊
[翻譯] Google 建議的 Python 風格指南 7 原文網址:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html * list comprehension 在邏輯簡單的情況下可以使用 list comprehension 釋義: list comprehension 與 generator expression 可以很簡約而有效率的產生 list 及 iterator,而且不需要用到 map(), filter(), lambda 函數。 優點: List comprehension 比其他產生 list 的技巧要清楚而簡約。Generator 的表示 法效率很高,因為他們避免一次產生整個 list。 缺點: 複雜的 list comprehension 或 generator expression 不易讀懂。 決策: 在邏輯簡單的情況下可以使用它們。每一個組成部份都應在一行內結束,這些組成 部份包括:mapping 敘述、for 子句、filter 敘述。若需要超過一個的 for 子句 或超過一個的 filter 敘述,代表該邏輯已經過於複雜,不應該使用 list comprehension 或 generator expression,而應該使用迴圈來完成。 正確的例子 1: result = [] for x in range(10): for y in range(5): if x * y > 10: result.append((x, y)) 錯誤的例子 1: result = [(x, y) for x in range(10) for y in range(5) if x * y > 10] 正確的例子 2: for x in xrange(5): for y in xrange(5): if x != y: for z in xrange(5): if y != z: yield (x, y, z) 錯誤的例子 2: return ((x, y, z) for x in xrange(5) for y in xrange(5) if x != y for z in xrange(5) if y != z) 其他正確的例子: return ((x, complicated_transform(x)) for x in long_generator_function(parameter) if x is not None) squares = [x * x for x in range(10)] eat(jelly_bean for jelly_bean in jelly_beans if jelly_bean.color == 'black') -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 75.102.68.81
timTan:清楚! 05/01 22:00
ya790206:有人覺得 list comprehension 違反 There should be one- 05/01 23:06
ya790206:There should be one-- and preferably only one --obvio 05/01 23:06
ya790206:--obvious way to do it. 規則嗎? 我覺得現在python 有 05/01 23:07
ya790206:太多方法可以去作同一件事。 05/01 23:08
kdjf:list comp 就是那一個obvious way啊... 05/02 08:37