Nobi
Nobi

Reputation: 1109

Grouping the content of nested tuples

please can anyone help me with this code snippet below

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

Gave the output:

[5, 4, 0, 7]

But is there a way to rewrite it so the output will be so:

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

Thanks

Upvotes: 2

Views: 58

Answers (2)

thefourtheye
thefourtheye

Reputation: 239473

It would be better if you could convert the lst1 to a dictionary like this

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

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

You can do it as follows:

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

Upvotes: 1

Related Questions