python - 根据元组列表(值、索引)创建列表

标签 python list

我输入了一个包含字符串和整数列表的元组列表。整数从 1n 并且它们最多出现一次:

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/

相关文章:

python - 从 Pandas 单元格中提取列表并使用列表元素作为新列

python - 在python中查找列表中的序列索引

python - 在 Windows 上通过 Apache Lounge 部署 Flask 应用程序时出现内部服务器错误

arrays - PowerShell 枚举一个只包含一个内部数组的数组

c++ - 对同一对象同时使用 Map 和 List

java - Java中接口(interface)和列表的返回类型和参数?

python - 如何遍历列表的前 n 个元素?

python - .txt 文件中的 NumPy 数组太大,无法加载到内存中

python - 从现有模型中分解出新模型时创建迁移

python - 如何检查第一个列表是否以相同的顺序出现在第二个列表中的某个位置