itertools.chain
只需制作一个生成器,因此如果您可以使用生成器而不是列表来摆脱困境,那么生成的时间是恒定的,但是您在访问每个元素时会付出代价。否则list_a[0:0] = list_b
大约快 6 倍list_a = list_b + list_a
我认为这list_a = list_b + list_a
是最易读的选择,而且已经相当快了。
您提到的append()
在for
循环中使用的两种方法非常慢,所以我没有费心将它们包括在内。
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
使用以下代码在 1.6 GHz 双核 Intel Core i5 和 16 GB 2133 MHz LPDDR3 RAM 上运行Python 3.7.5 :
from timeit import timeit
import random
import matplotlib.pyplot as plt
num_data_points = 1000
step = 10
methods = [
# ordered from slowest to fastest to make the key easier to read
# """for item in list_a: list_b.append(item); list_a = list_b""",
# """for item in list_b: list_a.insert(0, item)""",
# "list_a = list(itertools.chain(list_b, list_a))",
"list_a = list_b + list_a",
"list_a[0:0] = list_b",
"list_a = itertools.chain(list_b, list_a)",
]
x = list(range(0, num_data_points * step, step))
y = [[] for _ in methods]
for i in x:
list_a = list(range(i))
list_b = list(range(i))
random.shuffle(list_a)
random.shuffle(list_b)
setup = f"list_a = {list_a}; list_b = {list_b}"
for method_index, method in enumerate(methods):
y[method_index].append(timeit(method, setup=setup, number=30))
print(i, "out of", num_data_points * step)
ax = plt.axes()
for method_index, method in enumerate(methods):
ax.plot(x, y[method_index], label=method)
ax.set(xlabel="number of elements in both lists", ylabel="time (s) (lower is better)")
ax.legend()
plt.show()