簡體   English   中英

我有 2 個元組列表,如何打印元組的第二個元素之間的差異,同時讓第一個元素保持不變?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM