假设我有一个像[(1,2), (1,3), (1,4), (1,5), (1,6)]这样的元组列表。我试图把它转换成一个简单的列表,比如[1,2,1,3,1,4,1,5,1,6]。
如何做到这一点,而不必迭代每个元素,并将项目逐个添加到另一个列表中?
是否有任何快速和有效的方法来做到这一点,而不实际迭代原来的元组列表?也许是内置的函数或方法?
发布于 2012-09-10 16:08:27
lst = [(1,2), (1,3), (1,4), (1,5), (1,6)]
import itertools
list(itertools.chain(*lst))
# [1, 2, 1, 3, 1, 4, 1, 5, 1, 6]另一种选择是:
[e for l in lst for e in l]
# [1, 2, 1, 3, 1, 4, 1, 5, 1, 6]发布于 2012-09-10 17:44:36
“Fundamentally,哪个更快?使用“迭代工具”模块,还是使用列表理解?我基本上是想提高我的计算速度,here.” - @davidadamojr
我一直在做一些测试,我发现下面的代码实际上更快。
list_ = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)]
list(sum(list_, ()))如果我错了谁来纠正我。
下面是一些测试。
>>> list_ = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)]
>>>
>>> operation_1 = lambda: [tuple_item for tuple_ in list_ for tuple_item in tuple_]
>>> def operation_2 ():
final_list = []
for tuple_ in list_:
for tuple_item in tuple_:
final_list.append(tuple_item)
return final_list
>>> operation_3 = lambda: reduce(list.__add__, map(list, list_))
>>> def operation_4 ():
import itertools
return list(itertools.chain(*list_))
>>> operation_5 = lambda: list(sum(list_, ()))
>>>
>>> operation_1()
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]
>>> operation_2()
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]
>>> operation_3()
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]
>>> operation_4()
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]
>>> operation_5()
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]
>>>
>>> import timeit
>>>
>>> print('operation_1 completed in %s seconds.' % (timeit.timeit(operation_1)))
operation_1 completed in 1.57890490223 seconds.
>>> print('operation_2 completed in %s seconds.' % (timeit.timeit(operation_2)))
operation_2 completed in 2.90350501659 seconds.
>>> print('operation_3 completed in %s seconds.' % (timeit.timeit(operation_3)))
operation_3 completed in 5.08437990236 seconds.
>>> print('operation_4 completed in %s seconds.' % (timeit.timeit(operation_4)))
operation_4 completed in 3.85125378138 seconds.
>>> print('operation_5 completed in %s seconds.' % (timeit.timeit(operation_5)))
operation_5 completed in 1.2623826489 seconds.发布于 2012-09-10 16:22:40
使用chain.from_iterable,因为它避免了不必要的一次性解压缩(这会导致冗余内存消耗),因为它懒洋洋地推进列表:
>>> import itertools
>>> L = [(1,2), (1,3), (1,4), (1,5), (1,6)]
>>> list(itertools.chain.from_iterable(L))
[1, 2, 1, 3, 1, 4, 1, 5, 1, 6]https://stackoverflow.com/questions/12355442
复制相似问题