gpt4 book ai didi

python - 具有可变数量元素的附加拆包概括 (PEP 448)

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:48 28 4
gpt4 key购买 nike

接受PEP 448 Python 3.5 中引入了其他解包通用化

例如:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]

# unpack both iterables in a list literal
>>> joinedList = [*l1, *l2]
>>> print(joinedList)
[1, 2, 3, 4, 5, 6]

问题:有没有办法对列表列表执行类似的操作?

此代码不起作用:

SyntaxError: iterable unpacking cannot be used in comprehension

# List of variable size
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = [*l for l in list_of_lists]

当然,您可以执行以下操作,但这看起来不太优雅且效率不高:

# List of variable size
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = list()
for l in list_of_lists:
joined_list += l

最佳答案

老派怎么样:sum()

代码:

joined_list = sum(list_of_lists, [])

测试代码:

# List of variable size
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = sum(list_of_lists, [])
print(joined_list)

结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

关于python - 具有可变数量元素的附加拆包概括 (PEP 448),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738962/

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