您可以尝试这个方法:
dct = {1:2, 3:4, 5:6, 7:8}
out = [None] * 2*len(dct)
for idx, (out[2*idx],out[2*idx+1]) in enumerate(dct.items()):
pass
print(out)
输出:
[1, 2, 3, 4, 5, 6, 7, 8]
使用dictionary
检查运行时,其大小为50_000_000
:(在colab上)
from timeit import timeit
import operator, functools
from itertools import chain
def approach1(dct):
li = []
for k, v in dct.items():
li.extend([k,v])
return li
def approach2(dct):
out = [None] * 2*len(dct)
for idx, (out[2*idx],out[2*idx+1]) in enumerate(dct.items()):
pass
return (out)
def approach3(dct):
return functools.reduce(operator.iconcat, dct.items(), [])
def approach4(dct):
return list(chain.from_iterable(dct.items()))
def approach5(dct):
return [i for t in dct.items() for i in t]
funcs = approach1, approach2, approach3, approach4, approach5
dct = {i:i for i in range(50_000_000)}
for _ in range(3):
for func in funcs:
t = timeit(lambda: func(dct), number=1)
print('%.3f s ' % t, func.__name__)
print()
输出:
8.825 s approach1
13.243 s approach2
4.506 s approach3
3.809 s approach4
7.881 s approach5
8.391 s approach1
13.159 s approach2
4.487 s approach3
3.854 s approach4
7.946 s approach5
8.391 s approach1
13.197 s approach2
4.448 s approach3
3.681 s approach4
7.904 s approach5
检查使用不同尺寸的字典
的运行时:(在colab上)
from timeit import timeit
import operator, functools
from itertools import chain
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def app_extend(dct):
li = []
for k, v in dct.items():
li.extend([k,v])
return li
def app_enumerate(dct):
out = [None] * 2*len(dct)
for idx, (out[2*idx],out[2*idx+1]) in enumerate(dct.items()):
pass
return (out)
def app_functools(dct):
return functools.reduce(operator.iconcat, dct.items(), [])
def app_chain(dct):
return list(chain.from_iterable(dct.items()))
def app_for(dct):
return [i for t in dct.items() for i in t]
funcs = app_extend, app_enumerate, app_functools, app_chain, app_for
dct_rslt = {}
for dct_size in [100_000, 250_000, 500_000, 1_000_000, 2_500_000, 5_000_000, 10_000_000, 25_000_000, 50_000_000]:
dct = {i:i for i in range(dct_size)}
dct_rslt[str(dct_size)] = {func.__name__ : timeit(lambda: func(dct), number=1) for func in funcs}
df = pd.DataFrame(dct_rslt).T
fig, ax = plt.subplots()
fig.set_size_inches(12, 9)
sns.lineplot(data=df)
plt.xlabel('Dictionary Size')
plt.ylabel('Time(sec)')
plt.show()
![enter image description here](https://istack.dev59.com/IaH6k.webp)
range
中的整数字面量以提高可读性。 - Wolf