[英]Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple
[英]I have 2 lists of tuples, how can I print the difference between the second element of the tuples while leaving the first element the same?
例如,我有两个列表:
[('Joe', 10), ('Tim', 14), ('Toby', 20)]
[('Joe', 8), ('Tim', 18), ('Toby', 12)]
我希望它打印:
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
做这个的最好方式是什么?
考虑使用collections.Counter
,它具有dict.update
的“减法”版本。 例如:
>>> L1 = [('Joe', 10), ('Tim', 14), ('Toby', 20)]
>>> L2 = [('Joe', 8), ('Tim', 18), ('Toby', 12)]
>>> from collections import Counter
>>> c1 = Counter(dict(L1))
>>> c1.subtract(Counter(dict(L2)))
>>> print(list(c1.items()))
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
一种方法是zip
内容,然后解析每个压缩对,在那时进行数学和名称提取。
zip
将生成一个可迭代对象,该对象将生成一对项目,从每个输入项目拉链到一起......如果你要查看这些对,它们看起来像这样:
(('Joe', 10), ('Joe', 8))
(('Tim', 14), ('Tim', 18))
(('Toby', 20), ('Toby', 12))
配对每个项目后,操作或处理每个项目就相当简单了。
>>> l1 = [('Joe', 10), ('Tim', 14), ('Toby', 20)]
>>> l2 = [('Joe', 8), ('Tim', 18), ('Toby', 12)]
>>> new_list = []
>>> for element1, element2 in zip(l1, l2):
... new_list.append((element1[0], element1[1] - element2[1]))
...
>>> new_list
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
如果名称匹配,我认为您想减去这些值。 尝试这个:
first = [('Joe', 10), ('Tim', 14), ('Toby', 20)]
second = [('Joe', 8), ('Tim', 18), ('Toby', 12)]
access_dict = {} # used for matching the names
for name, value in first:
access_dict[name] = value # add to matcher dict
for name, value in second:
if name in access_dict: # skip if corresponding name was not in first
access_dict[name] = access_dict[name] - value # subtract value
print(list(access_dict.items()))
输出:
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
注意:这不会保留名称的顺序
您可以使用列表理解:
l1=[('Joe', 10), ('Tim', 14), ('Toby', 20)]
l2=[('Joe', 8), ('Tim', 18), ('Toby', 12)]
>>> [(t1[0],t1[1]-t2[1]) for t1,t2 in zip(l1,l2)]
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
如果合适,您可以添加测试以确保元组的第一部分相同:
[(t1[0],t1[1]-t2[1]) for t1,t2 in zip(l1,l2) if t1[0]==t2[0]]
但是,如果您的列表可能包含不匹配的元组,那么使用计数器的wim版本是最健壮的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.