比较嵌套的元组列表

时间:2014-05-01 21:44:28

标签: python

嗨,我怎么能循环通过lst2,检查匹配的那些,并在相应的字典中总结v的值。

即。如果lst2中(' 1',' 2')的元素与' 1',' 2'匹配在lst1中,获取v即5的值,并为该列表列表中的所有元组添加v值。

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

output should be vol = 5 + 4 = 9 for [('1','2'),('2','9')] 

请我试过这个,它确实给出了所需的输出。请帮忙

vol = []
f = 0.0
for b in lst2:
    if  float(b[0][0]) == float(lst1[0][0]) and float(b[0][0])== float(lst1[0][1]):
        f = f + float(lst1[0][0][v])
        vol.append(f)

1 个答案:

答案 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 elem in lst2:
    for sub_e in elem:
        for l in lst1:
            if  l[0:2] == sub_e:
                vol.append(l[2]["v"])
 In [4]: print vol
 [5, 4, 0, 7]

 In [5]: print sum(vol)
 16


To pair the output:

pairs=[]
for i in xrange(0,len(vol),2) :
    pairs.append([vol[i],vol[i+1]])
In [10]: pairs
Out[10]: [[5, 4], [0, 7]]

# even and odd length lists
pairs=[]
vol_it = iter(vol)
for i,j in zip(vol_it, vol_it):
   pairs.append([i,j])
if len(vol) %2 ==1:
    pairs.append([vol[-1]])

In [28]:  vol=[1,2,3,4,5,6]

In [29]: pairs
Out[30]: [[1, 2], [3, 4], [5, 6]]

In[31]: vol=[1,2,3,4,5]
In [31]: pairs
Out[31]: [[1, 2], [3, 4], [5]]


using  itertools:

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
print [[x[0],x[1]]for x in (grouper(vol,2)) ]

这就是你想要的吗?

In [6]: paste
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"])

## -- End pasted text --

In [7]: print sum(vol)
16

In [8]: print vol
[5, 4, 0, 7]