How to use list comprehension with .extend list me

2019-01-29 06:19发布

问题:

This question already has an answer here:

  • How can I use a list comprehension to extend a list in python? [duplicate] 6 answers

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?

回答1:

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))


回答2:

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)