我试图找到一种简短而优雅的方式来访问嵌套列表中的所有单个元素。例如:
lst1 = ['1', '2', '3']
lst2 = ['4', '5']
outer = [lst1, lst2]
是否存在返回['1', '2', '3', '4', '5']
的列表推导式?
有两种简短的类似方法:
import itertools
# with unpacking
list(itertools.chain(*outer))
# without unpacking
list(itertools.chain.from_iterable(outer))
import itertools
lst1 = ['1', '2', '3']
lst2 = ['4', '5']
outer = [lst1, lst2]
flattened = list(itertools.chain(*outer))
['1', '2', '3', '4', '5']