[英]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?
Example, I have two lists:例如,我有两个列表:
[('Joe', 10), ('Tim', 14), ('Toby', 20)]
[('Joe', 8), ('Tim', 18), ('Toby', 12)]
I want it to print:我希望它打印:
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
What is the best way to do this?做这个的最好方式是什么?
Consider using a collections.Counter
, which features a "subtraction" version of dict.update
.考虑使用collections.Counter
,它具有dict.update
的“减法”版本。 For example:例如:
>>> 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)]
An approach is to zip
the contents and then parse each zipped pair, doing the math and name extraction at that time.一种方法是zip
内容,然后解析每个压缩对,在那时进行数学和名称提取。
zip
will produce an iterable that will generate a pair of items, zippered together from each of the input items... If you were to look at these pairs, the would look something like this: zip
将生成一个可迭代对象,该对象将生成一对项目,从每个输入项目拉链到一起......如果你要查看这些对,它们看起来像这样:
(('Joe', 10), ('Joe', 8))
(('Tim', 14), ('Tim', 18))
(('Toby', 20), ('Toby', 12))
With each item paired, it is fairly straightforward to then manipulate OR process each pair.配对每个项目后,操作或处理每个项目就相当简单了。
>>> 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)]
I think you want to subtract the values if the names match.如果名称匹配,我认为您想减去这些值。 Try this:尝试这个:
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()))
Output:输出:
[('Joe', 2), ('Tim', -4), ('Toby', 8)]
Note: this does not preserve the order of the names注意:这不会保留名称的顺序
You can use a list comprehension:您可以使用列表理解:
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)]
You can add a test to make sure that the first part of the tuple is the same if appropriate:如果合适,您可以添加测试以确保元组的第一部分相同:
[(t1[0],t1[1]-t2[1]) for t1,t2 in zip(l1,l2) if t1[0]==t2[0]]
But wim's version using a counter is the most robust if you have lists that might have mismatched tuples.但是,如果您的列表可能包含不匹配的元组,那么使用计数器的wim版本是最健壮的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.