How to use list comprehension with .extend list me

2019-01-29 05:41发布

This question already has an answer here:

For example, this snippet:

out = []
for foo in foo_list:
    out.extend(get_bar_list(foo)) # get_bar_list return list with some data
return out

How to shorten this code using list comprehension?

2条回答
太酷不给撩
2楼-- · 2019-01-29 06:18

You can use a nested list-comprehension:

out = [foo for sub_item in foo_list for foo in get_bar_list(sub_item)]

FWIW, I always have a hard time remembering exactly what order things come in for nested list comprehensions and so I usually prefer to use itertools.chain (as mentioned in the answer by Moses). However, if you really love nested list-comprehensions, the order is the same as you would encounter them in a normal loop (with the innermost loop variable available for the first expression in the list comprehension):

for sub_item in foo_list:
    for foo in get_bar_list(sub_item):
        out.append(foo)
查看更多
别忘想泡老子
3楼-- · 2019-01-29 06:40

You can use a generator expression and consume it with itertools.chain:

from itertools import chain

out = list(chain.from_iterable(get_bar_list(foo) for foo in foo_list))
查看更多
登录 后发表回答