【问题标题】:Compare two list and print number of times common elements apppear比较两个列表并打印常见元素出现的次数
【发布时间】:2015-02-10 02:05:01
【问题描述】:

我想将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)

【问题讨论】:

  • 那你有什么问题?
  • 顺便说一句,您不需要 random 库。
  • drawsitems 在哪里?
  • @Rinzler 是的,OP 似乎缺少一些代码(random 库未使用,drawsitems 不存在等)

标签: python python-2.7 list-comparison


【解决方案1】:

试试下面的代码:

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]]

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 2019-01-17
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多