我输入了一个包含字符串和整数列表的元组列表。整数从 1
到 n
并且它们最多出现一次:
l = [('red', [0,2,5]),
('yellow', [1,4]),
('red', [6])]
我想创建一个 n
字符串列表,如果索引出现在其中一个列表中,它的值将是相应的字符串,如果它没有出现,将应用默认值,例如 white
。
这是预期的输出:
result = ['red', 'yellow', 'red', 'white', 'yellow', 'red', 'red']
这是我的代码,它运行良好,但我想知道是否有更快的方法:
result = ['white'] * n
for t in l:
for i in t[1]:
result[i] = t[0]
编辑:
我忘了说 n
大约是 300。
最佳答案
对于 python 中所有“是否有更快的方法来做到这一点”的问题(我相信,在大多数语言中也是如此),答案是测量它,然后你就会知道。
我采用了目前提出的答案中的代码并对其进行了计时:
import numpy as np
import timeit
n = 7
l = [('red', [0,2,5]),
('yellow', [1,4]),
('red', [6])]
def OP_approach():
result = ['white'] * n
for t in l:
for i in t[1]:
result[i] = t[0]
return result
def yatu_approach():
d = {j:i[0] for i in l for j in i[1]}
return [d.get(i, 'white') for i in range(len(d)+1)]
def blue_note_approach():
x = np.empty(7, dtype='<U5')
x.fill('white')
for a, b in l:
x[b] = a
return x
timeit.timeit(OP_approach, number=10000)
timeit.timeit(yatu_approach, number=10000)
timeit.timeit(blue_note_approach, number=10000)
令我惊讶的是,这是我机器(arm64 板)上的结果:
>>> timeit.timeit(OP_approach, number=10000)
0.033418309001717716
>>> timeit.timeit(yatu_approach, number=10000)
0.10994336503790691
>>> timeit.timeit(blue_note_approach, number=10000)
0.3608954470255412
看来,对于给定的样本数据,简单的双循环比其他两个选项都快。但是请记住,正如@yatu 所指出的,这些算法的规模非常不同,使用哪种算法的选择取决于要解决的问题的预期规模。
关于python - 根据元组列表(值、索引)创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253184/