比较两个列表中的元组值

时间:2014-11-22 07:02:45

标签: python-2.7

**for i in range(a):
    p=int(raw_input("Enter Elements in List1:"))
    list1.append(p)
    d1=defaultdict(int)
    for item in list1:
        d1[item]+=1
print list1
print d1.items()
print ""**

如何比较以下列表输出中的元组值? 在这里,我的答案应该返回元组值(207,2),(208,1)和(209,1),因为这两个列表中的元素相同。

input1 : [203, 203, 204, 204, 205, 206, 207, 208, 207, 209]

output1: [(203, 2), (204, 2), (205, 1), (206, 1), (207, 2), (208, 1), (209, 1)]

input2:  [204, 203, 205, 205, 206, 206, 207, 207, 208, 209, 205, 206, 205]

output2: [(203, 1), (204, 1), (205, 4), (206, 3), (207, 2), (208, 1), (209, 1)]

1 个答案:

答案 0 :(得分:0)

您可以使用Counter

>>> from collections import Counter
>>> lst = [203, 203, 204, 204, 205, 206, 207, 208, 207, 209]
>>> freqs = Counter(lst)
>>> freqs
Counter({203: 2, 204: 2, 207: 2, 205: 1, 206: 1, 208: 1, 209: 1})
>>> lst2 = [204, 203, 205, 205, 206, 206, 207, 207, 208, 209, 205, 206, 205]
>>> Counter(lst2)
Counter({205: 4, 206: 3, 207: 2, 203: 1, 204: 1, 208: 1, 209: 1})

首先比较方法:

>>> [ k  for k,v in Counter(lst2).iteritems() if v == Counter(lst)[k] ]
[207, 208, 209]

第二种比较方法:

>>> for k,v in Counter(lst2).iteritems():
...     if v == Counter(lst)[k]:
...             print k
... 
207
208
209