操作列表和字典列表

时间:2016-09-23 14:25:58

标签: python python-2.7 dictionary

我有一个表示字典中键的列表。我希望为列表中的每个列表拾取较小的键。例如,

L1 = [['1_A','2_A'],['1_B','2_B']]
D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373}

for li in L1:
    for ll in li:
        if ll in D1.keys():
            print "Value for %s is %s" %(ll,D1[ll])
        else:
            print "Values not found"

当我打印它时,我得到:

Value for 1_A is 0.22876
Value for 2_A is 0.22382
Value for 1_B is 0.2584
Value for 2_B is 0.25373

我期望的输出为2_A2_B,因为它们分别与1_A1_B相比具有较小的值。谁能建议怎么做?

2 个答案:

答案 0 :(得分:2)

您没有在任何地方比较这些值。

L1 = [['1_A','2_A'],['1_B','2_B']]
D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373}

template = "Value for {} is {}"

for i,j in L1:
    if D1[i] < D1[j]:
        print template.format(i,D1[i])
    else:
        print template.format(j,D1[j])

答案 1 :(得分:0)

我找到了另一个简单的答案!

adTinyInt

列表理解版本:

L1 = [['1_A','2_A'],['1_B','2_B']]
D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373}

for i in L1:
    val = (sorted(i, key=D1.get))[0]
    newlist.append(val)

"newlist = ['2_A', '2_B']"

谢谢!