about 3 years ago

Avoid More Than Two Expressions in List Comprehensions

Google 自己的 style guide 也有提到

Okay to use for simple cases.
Each portion must fit on one line: mapping expression, for clause, fi lter expression.
Multiple for clauses or filter expressions are not permitted.
Use loops instead when things get more complicated

像這樣可讀性較低

my_lists = [
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]],
]
flat = [x for sublist1 in my_lists
        for sublist2 in sublist1
        for x in sublist2]

上面的程式用 for-loop 改寫會比較清楚

flat = []
for sublist1 in my_lists:
    for sublist2 in sublist1:
        flat.extend(sublist2)
← Effective Python 心得筆記: Item 7 Effective Python 心得筆記: Item 9 →
 
comments powered by Disqus