何かを書き留める何か

数学や読んだ本について書く何かです。最近は社会人として生き残りの術を学ぶ日々です。

『Effective Python』Item 8: リスト内包表記では2つ以上の式を避ける

『Effective Python』の続き。邦訳は出るのですか。

Effective Python: 59 Specific Ways to Write Better Python (Effective Software Development Series)

Effective Python: 59 Specific Ways to Write Better Python (Effective Software Development Series)

www.effectivepython.com

list.appendよりもリスト内包表記のほうが効率がよいという話もあり、つい無理してリスト内包表記を使ってしますが、それを戒めるかのような項目である。

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]
print(flat)

のような複雑なリスト内包表記はやめましょう、という話である。

なお、この項目ではリストの平滑化を題材となっているが、実際に平滑化を行う際はitertoolsを使うとよい。

from itertools import chain

def flatten(listOfLists):
    return chain.from_iterable(listOfLists)

my_lists = [
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]],
]

flat_my_list = list(flatten(flatten(my_lists)))
print(flat_my_list)

うーん、わかりやすいだろうか…。

flattenで1段階平滑化するので2回利用している。 一発で多重化のレベルに依存しない平滑化の函数はかけるだろうか。