【问题标题】:Most efficient way to join several large lists加入多个大型列表的最有效方法
【发布时间】:2020-09-14 18:37:22
【问题描述】:

我有几个大列表。我想把它们合并成一个单一教派的名单。例如,

small_lists = [[{'value1':1}]*100000,[{'value2':2}]*100000,[{'value3':3}]*100000]
combined_list = []
for small_list in small_lists:
    combined_list.extend(small_list)

有没有比上面更快的方法?

在几个答案中建议使用numpy,但对我来说似乎要慢得多。我做错什么了吗?

import time
import numpy as np

small_lists = [[{'value1':1}]*10000000,[{'value2':2}]*10000000,[{'value3':3}]*10000000]

start = time.time()
np_list = np.array(small_lists).flatten()
print("{} sec".format(time.time() - start))
print(len(np_list))

start = time.time()
combined_list = []
for small_list in small_lists:
    combined_list.extend(small_list)
print("{} sec".format(time.time() - start))
print(len(combined_list))

from functools import reduce
start = time.time()
reduce_list = reduce(lambda x, y: x+y, small_lists)
print("{} sec".format(time.time() - start))
print(len(reduce_list))

numpy 的输出为 2.01335906982 秒,扩展为 0.113998889923 秒,reduce 为 0.299326896667 秒。 extend 是迄今为止最快的。

【问题讨论】:

  • 查看this answer 到一个相关(几乎重复)的问题,了解一些时间。
  • 还有this answer
  • numpy 并没有真正针对字典数组之类的东西进行优化。如果 numpy 更适合整数列表而不是字典列表,我不会感到惊讶。

标签: python list


【解决方案1】:

使用 numpy - 对于非常大的数组,这可以快 10-100 倍:

import numpy as np

np_array = np.array(small_list)
flat = np_array.flatten()

【讨论】:

  • 我做错什么了吗? numpy 对我来说似乎慢了很多。抱歉,我无法在此处插入代码。将对我原来的问题添加新评论
【解决方案2】:
from functools import reduce

combined_list = reduce(lambda x, y: x + y, small_lists)

https://docs.python.org/3.7/library/functools.html#functools.reduce

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多