我在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')]
我尝试了sum
它的不同方式,但直到现在还远没有幸运,因为我对python很新。关于如何实现这一点的任何建议?非常感谢你!
答案 0 :(得分:1)
这样做你想要的:
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)]