将列表与字典进行比较

时间:2014-03-31 04:33:07

标签: python-2.7

嗨,我怎么能比较点中的元素和pos中的键,并打印pos [values]即那些匹配的元组。谢谢

我试过这个

dots = [[1,2,73,4],[5,36,7,18]]
pos = {1:(0,6), 2:(4,3),3:(7,5),4:(9,0), 5:(0,28), 6:(4,3),7:(7,5),8:(9,0)}

 dot_pos = []
for k in dots:
    for item in k:
        if item in pos:
            dot_pos.append(pos[key])

并收到此错误:

    ValueError: too many values to unpack

请更新

如何解决此问题以获得这样的输出:

[[(0, 6), (4, 3), (9, 0)],[ (0, 28), (7, 5]] 

4 个答案:

答案 0 :(得分:1)

试试这个。你在代码的最后一行使用了密钥,这是未定义的。

dots = [[1,2,73,4],[5,36,7,18]]
pos = {1:(0,6), 2:(4,3),3:(7,5),4:(9,0), 5:(0,28), 6:(4,3),7:(7,5),8:(9,0)}

dot_pos = []
for k in dots:
    for item in k:
        if item in pos:
            dot_pos.append(pos[item])

对于您的第二个评论问题,这应该有效:

dot_pos = []
for k in dots:
    dot_new = []  
    for item in k:
        if item in pos:
            dot_new.append(pos[item]) #Append the matches to a new list
    dot_pos.append(dot_new)           

答案 1 :(得分:1)

for i in dots:

    for item in i:

        if(item in pos.keys()):

            print(pos[item])

答: (0,6) (4,3) (9,0) (0,28) (7,5)

答案 2 :(得分:1)

l=list();
for i in dots:
    a=[]; // one list per element (which is list) in dots
    for item in i:
        if item in pos.keys():
            a.append(pos[item]);
    l.append(a)

// print(l)

// [[(0,6),(4,3),(9,0)],[(0,28),(7,5)]]

答案 3 :(得分:1)

请注意,您可以使用理解直接提取点数。例如,如果您有:

In [44]: pos = {1:(0,6), 2:(4,3),3:(7,5),4:(9,0), 5:(0,28), 6:(4,3),7:(7,5),8:(9,0)}
In [45]: dots1 = [1,2,73,4]
In [46]: [pos[dot] for dot in dots1 if dot in pos.keys()]
Out[46]: [(0, 6), (4, 3), (9, 0)]

因此,如果您有一个临时功能,那么:

In [49]: def f(dots1): return [pos[dot] for dot in dots1 if dot in pos.keys()]

然后你可以将功能映射到点......

In [50]: f(dots1)
Out[50]: [(0, 6), (4, 3), (9, 0)]
In [51]: dots = [[1,2,73,4],[5,36,7,18]]
In [52]: map(f, dots)
Out[52]: [[(0, 6), (4, 3), (9, 0)], [(0, 28), (7, 5)]]
相关问题