繁体   English   中英

比较元组的嵌套列表

[英]Comparing nested list of tuples

嗨,请问我如何遍历lst2,检查是否匹配并在对应的字典中对v的值求和。

例如,如果lst2中的('1','2')的元素与lst1中的'1','2'匹配,则获取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)
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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM