gpt4 book ai didi

python - 在列表理解中使用列表解包来展平嵌套列表

转载 作者:行者123 更新时间:2023-11-30 22:31:28 24 4
gpt4 key购买 nike

我看到了this合并列表的解决方案,例如 a = [1,2,3], b = [4,5,6]使用res = [*a, *b] .

假设我有一个子列表列表,例如 ls = [a,b]是否可以做类似 res = [*i for i in ls] 的事情?

该特定行自 SyntaxError: iterable unpacking cannot be used in comprehension 起无效。可以做类似的事情吗?

如果没有,如何轻松创建一个包含子列表中所有元素的列表?

使用 python 3.5.3

最佳答案

不,我不相信他们已经在理解中添加了对列表解包的支持。

作为替代方案,您可以使用itertools.chain:

>>> from itertools import chain
>>> list(chain.from_iterable([a, b]))
[1, 2, 3, 4, 5, 6]

或者,嵌套循环列表理解:

>>> [y for x in [a, b] for y in x]
[1, 2, 3, 4, 5, 6]

关于python - 在列表理解中使用列表解包来展平嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com