比较两个列表和打印常见元素出现的次数

时间:2015-02-10 02:05:02

标签: python python-2.7 list-comparison

我想将items1items2进行比较,并打印items2中显示的items1中最常见的数字。

items1中的数字是固定的,items2中的数字会更新。我还想计算每个数字出现的次数。这是我到目前为止所提出的:

import collections

items1 = [12, 23, 34, 45, 56, 67, 78, 89, 13, 24, 35, 46, 57, 68, 79, 014]
items2 = [528, 98, 925, 902, 67, 78, 89, 13, 24, 35, 46, 57]
results = collections.Counter()

for _ in items:
    number = (draws)
    results.update([tuple(number)])

print results.most_common(3)

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

items1 = [12, 23, 34, 45, 56, 67, 78, 89, 13, 24, 35, 46, 57, 68, 79, 014]
items2 = [528, 98, 925, 902, 67, 78, 89, 13, 24, 35, 46, 57]
itemcount = {item: items2.count(item) for item in items1}

print [[number, itemcount[number]] for number in sorted(itemcount.keys(), key=lambda x:itemcount[x])[::-1][:5]] 
#Prints [common value: occurences], as such: [[89, 1], [46, 1], [35, 1], [24, 1], [13, 1]]