有什么方法可以动态地在特定列表中插入值?

时间:2019-06-13 20:07:54

标签: python list variables

我正在尝试使用变量名动态地在列表中插入值,但我无法做到这一点。

lst_prio = [90, 100]
p_90 = [0.11, 0.2, 0.15, 0.6, 0.9]
p_100 = [0.1, 0.3, 0.5, 0.7, 0.8]
lst_crv = [4,3,2,5,6]
crv = [1,2,3,4,5]

lst_percs = []
for x in range(len(lst_prio)):
    lst_percs.append("lst_p_"+str(lst_prio[x]))

dic =dict(zip(lst_prio,lst_percs))

for w in range(len(lst_prio)):
    dic[lst_prio[w]] =[]
    for i in range(len(crv)):
        for j in range(len(lst_crv)):
            if crv[i] == lst_crv[j]:
#Below I would like to insert the list as the append value (p_90 to p_100) dynamically based on the dictionary I've created 
                dic[lst_prio[w]].append(p_90[i])

我得到的结果(因为我无法迭代):

lst_p_90 = [0.2, 0.15, 0.6, 0.9]

lst_p_90 = [0.2, 0.15, 0.6, 0.9]

我想要的结果:

lst_p_90 = [0.2, 0.15, 0.6, 0.9]

lst_p_100 = [0.3, 0.5, 0.7, 0.8]

1 个答案:

答案 0 :(得分:0)

我想我明白你的意思。您要根据名称动态评估变量。在最后几行尝试一下。

    if crv[i] == lst_crv[j]:
        number = lst_prio[w]
        p_n = locals()['p_' + str(number)]
        dic[number].append(p_n[i])

相关:How to get the value of a variable given its name in a string?