Python 3.x 对元组列表的前三个值求和,并将结果追加到元组列表

Python 3.x 对元组列表的前三个值求和,并将结果追加到元组列表,python-3.x,sum,tuples,Python 3.x,Sum,Tuples,我在python 3.2中有一个元组列表,如下所示: d = [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose annoyed'), (['light', '99', 'lights', '1'], 'jimmy dimmed '), (['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted '), (['world', '8

我在python 3.2中有一个元组列表,如下所示:

d = [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose   annoyed'), 
(['light', '99', 'lights', '1'], 'jimmy dimmed '),
(['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted '), 
(['world', '8', 'painting', '6', 'website', '4', 'game', '4'], 'ralph created'),
(['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5'], 'aaron popped')]
我需要做的是对每个元组的前三项求和,并将结果附加到元组的末尾,这样结果将如下所示:

d2 = [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose   annoyed', '25'), 
(['light', '99', 'lights', '1'], 'jimmy dimmed ', '100'),
(['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted ', '76'), 
(['world', '8', 'painting', '6', 'website', '4', 'game', '4'], 'ralph created', '18'), 
(['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5'], 'aaron popped', '22')]

我尝试了不同的方法来求和,但直到现在我还不算幸运,因为我对python还很陌生。对如何实现这一点有何建议?多谢各位

这就是您想要的:

d = [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose   annoyed'), 
(['light', '99', 'lights', '1'], 'jimmy dimmed '),
(['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted '), 
(['world', '8', 'painting', '6', 'website', '4', 'game', '4'], 'ralph created'),
(['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5'], 'aaron popped')]

d2=[]
for t in d:
    tup=[t[0]]
    tup.append(t[1])
    tup.append(sum(int(x) for x in t[0][1::2]))
    d2.append(tuple(tup))

print(d2)
# [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose   annoyed', 25), 
   (['light', '99', 'lights', '1'], 'jimmy dimmed ', 100), 
   (['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted ', 80), 
   (['world', '8', 'painting', '6', 'website', '4', 'game', '4'], 'ralph created', 22), 
   (['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5'], 'aaron popped', 27)]
如果要限制列表中前3项的总和:

d2=[]
for t in d:
    tup=[t[0]]
    tup.append(t[1])
    tup.append(sum(int(x) for x in t[0][1:6:2]))
    d2.append(tuple(tup))

print(d2)
# [(['dog', '9', 'teacher', '9', 'neighbor', '7'], 'rose   annoyed', 25), 
   (['light', '99', 'lights', '1'], 'jimmy dimmed ', 100), 
   (['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 'aaron evicted ', 76),
   (['world', '8', 'painting', '6', 'website', '4', 'game', '4'], 'ralph created', 18), 
   (['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5'], 'aaron popped', 22)]

你为什么要这么做?这似乎是一种非常奇怪的方式来组织你的数据。完美!!非常感谢你!第二个解决方案正是我想要的!