【发布时间】:2021-02-16 13:49:27
【问题描述】:
所以我有一个函数,它将可变数量的列表作为参数,然后将这些列表组合成一个列表:
def comb_lists(*lists):
sublist = []
for l in lists:
sublist.extend(l)
print(sublist)
>>> comb_lists([1, 2], [3, 4], [5, 6])
[1, 2, 3, 4, 5, 6]
而且它有效。但我只是想知道是否有更简单的解决方案?我尝试了使用列表解包的列表推导,但返回了 SyntaxError:
def comb_lists(*lists):
sublist = [*l for l in lists]
>>> comb_lists([1, 2], [3, 4], [5, 6])
SyntaxError: iterable unpacking cannot be used in comprehension
有没有更简洁或更快的方法来做到这一点?
编辑: itertools 看起来对这类事情非常有用。我很想知道是否有任何不依赖进口的方法。
【问题讨论】:
-
试试
list(itertools.chain(*lists))?
标签: python python-3.x list concatenation