对^{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
,因为它是Schlemiel the Painter's algorithm的一种形式。sum
实际上用str
禁止它;他们没有试图阻止所有的序列使用,以避免减慢sum
试图阻止每一个误用,但这仍然是一个坏主意。你知道吗问题是,这意味着每次都要构建越来越大的临时
list
,在构建下一个临时之后,通过一遍又一遍地复制到目前为止看到的所有东西,再加上新的东西,把上一个临时文件扔掉。如果第一个列表中有一百万个项目,并且您还有十个list
要连接到它,那么您至少复制了一千万个元素(即使其他十个list
是空的)。您的原始代码实际上更好,因为使用执行就地扩展的+=
操作符,在O(n)
(对于所有list
范围内的n
元素)中保持最差的性能,而不是O(n*m)
(对于m
list
范围内的n
元素)。你知道吗它还存在只对一个一致类型工作的问题;如果一些输入是
list
、一些tuple
和一些生成器,sum
将不工作(因为list.__add__
将不接受另一端的非list
操作数)。你知道吗所以别那么做。这是what ^{} and it's alternate constructor, ^{} were made for :
它保证
O(n)
,可以与任何您抛出的iterables一起工作,等等是的,很明显,如果你一块只有三个元素,那就不重要了。但是如果输入iterables的大小或iterables的数量任意大,或者类型不一致,
chain
将起作用,sum
将不起作用去老学校怎么样:^{}
代码:
测试代码:
结果:
相关问题 更多 >
编程相关推荐