【问题标题】:Comparing two lists and number of occurrences [duplicate]比较两个列表和出现次数[重复]
【发布时间】:2014-07-07 02:34:34
【问题描述】:

在 Python 中比较两个列表并检查出现的最佳方法是什么?

考虑一下

list1 = [a, b, c]
list2 = [a, b, c, d, e, f, g]

我需要两件事:

  • 检查list1 是否包含来自list2 的元素并返回True 或False
  • 检查 list2 中有多少项目 (len?) 在 list1 中并取回这些出现的整数

【问题讨论】:

    标签: python list python-2.7 comparison


    【解决方案1】:

    你想在这里使用集合:

    intersection = set(list1).intersection(list2)
    

    intersection 现在是来自list1 的所有元素的集合,这些元素也出现在list2 中。它的长度是出现的次数。

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多