如何使用.extend list方法使用列表理解? [英] How to use list comprehension with .extend list method?
本文介绍了如何使用.extend list方法使用列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,此代码段:
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?
推荐答案
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))
这篇关于如何使用.extend list方法使用列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文