比较列表和字典的元素并存储为列表列表

时间:2014-03-31 07:02:57

标签: python-2.7

以下代码

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])

Gave:

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

如何解决此问题以获得如下输出:

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

由于

3 个答案:

答案 0 :(得分:1)

对于您想要的OP,暂时创建一个列表并将该项添加到if块的列表中,然后在执行内部for循环后追加内容:

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 = list()
for k in dots:
    list_temp = list()
    for item in k:
        if item in pos:
            list_temp.append(pos[item])
    dot_pos.append(list_temp)

print dot_pos

答案 1 :(得分:0)

简单的封装工作就足够了。循环执行后,当你返回时,可能会返回这个:

return dot_pos

对于您需要的输出,

return [dot_pos]

答案 2 :(得分:0)

您提供的代码会将[(0, 6), (4, 3), (9, 0), (0, 28), (7, 5)]作为输出。 假设您希望得到您所解释的内容,代码可能如下所示:

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 = list()
for k in dots:
    temp = list()
    for item in k:
        if item in pos:
            temp.append(pos[item])
    dot_pos.append(temp)
print dot_pos