具有可变元素数的附加解包推广(PEP 448)

2024-10-02 00:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}的接受引入了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

Tags: ofinl1forsizevariablelistslist
2条回答

我不鼓励在这里使用sum,因为它是Schlemiel the Painter's algorithm的一种形式。sum实际上用str禁止它;他们没有试图阻止所有的序列使用,以避免减慢sum试图阻止每一个误用,但这仍然是一个坏主意。你知道吗

问题是,这意味着每次都要构建越来越大的临时list,在构建下一个临时之后,通过一遍又一遍地复制到目前为止看到的所有东西,再加上新的东西,把上一个临时文件扔掉。如果第一个列表中有一百万个项目,并且您还有十个list要连接到它,那么您至少复制了一千万个元素(即使其他十个list是空的)。您的原始代码实际上更好,因为使用执行就地扩展的+=操作符,在O(n)(对于所有list范围内的n元素)中保持最差的性能,而不是O(n*m)(对于mlist范围内的n元素)。你知道吗

它还存在只对一个一致类型工作的问题;如果一些输入是list、一些tuple和一些生成器,sum将不工作(因为list.__add__将不接受另一端的非list操作数)。你知道吗

所以别那么做。这是what ^{} and it's alternate constructor, ^{} were made for

from itertools import chain

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = list(chain.from_iterable(list_of_lists))

它保证O(n),可以与任何您抛出的iterables一起工作,等等

是的,很明显,如果你一块只有三个元素,那就不重要了。但是如果输入iterables的大小或iterables的数量任意大,或者类型不一致,chain将起作用,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]

相关问题 更多 >

    热门问题