更新:使用扩展进行展平但没有理解并且不使用列表作为迭代器(最快)
在检查了通过列表理解提供更快解决方案的下一个答案之后,dual for
我做了一些调整,现在它表现更好,首先执行 list(...) 拖了很大一部分时间,然后更改了列表对简单循环的理解也减少了一点。
新的解决方案是:
l = []
for row in output: l.extend(row)
旧的替换list
为[]
(有点慢但不多):
[l.extend(row) for row in output]
较旧(较慢):
用列表理解展平
l = []
list(l.extend(row) for row in output)
新扩展的一些时间和通过删除 [...] 的 list(...) 获得的改进:
import timeit
t = timeit.timeit
o = "output=list(zip(range(1000000000), range(10000000))); l=[]"
steps_ext = "for row in output: l.extend(row)"
steps_ext_old = "list(l.extend(row) for row in output)"
steps_ext_remove_list = "[l.extend(row) for row in output]"
steps_com = "[item for sublist in output for item in sublist]"
print(f"{steps_ext}\n>>>{t(steps_ext, setup=o, number=10)}")
print(f"{steps_ext_remove_list}\n>>>{t(steps_ext_remove_list, setup=o, number=10)}")
print(f"{steps_com}\n>>>{t(steps_com, setup=o, number=10)}")
print(f"{steps_ext_old}\n>>>{t(steps_ext_old, setup=o, number=10)}")
结果的时间:
for row in output: l.extend(row)
>>> 7.022608777000187
[l.extend(row) for row in output]
>>> 9.155910597999991
[item for sublist in output for item in sublist]
>>> 9.920002304000036
list(l.extend(row) for row in output)
>>> 10.703829122000116