对嵌套元组的内容进行分组

时间:2014-05-02 06:03:28

标签: python python-2.7

请任何人帮助我使用下面的代码段

lst1 = [('1','2',{"v" : 5, "a" : 3}),('7','9',{"v" : 7, "a" : 3}),('3','4',{"v" : 4, "a" : 3}),('1','6',{"v" : 0, "a" : 3}),('2','9',{"v" : 4, "a" : 3})]

lst2 = [[('1','2'),('2','9')], [('1','6'),('7','9')]]
vol = [] 

for elem in lst2:
    for sub_e in elem:
        for l in lst1:
            if  l[0:2] == sub_e:
                vol.append(l[2]["v"])

输出:

[5, 4, 0, 7]

但有没有办法重写它,所以输出将如此:

[[5, 4], [0, 7]]

由于

2 个答案:

答案 0 :(得分:1)

您可以按照以下方式执行此操作:

lst1 = [('1','2',{"v" : 5, "a" : 3}),('7','9',{"v" : 7, "a" : 3}),('3','4',{"v" : 4, "a" : 3}),('1','6',{"v" : 0, "a" : 3}),('2','9',{"v" : 4, "a" : 3})]

lst2 = [[('1','2'),('2','9')], [('1','6'),('7','9')]]
vol = [] 

for i,elem in enumerate(lst2):             #changed to enumerate
    vol.append([])                         #added empty list for each outer loop
    for sub_e in elem:
        for l in lst1:
            if  l[0:2] == sub_e:
                vol[i].append(l[2]["v"])   #changed vol to vol[i]

>>> print vol
[[5, 4], [0, 7]]

答案 1 :(得分:1)

如果你能将lst1转换成这样的字典

会更好
d = {item[:2]:item[2]["v"] for item in lst1}
print [[d[item] for item in items if item in d] for items in lst2]
# [[5, 4], [0, 7]]