【问题标题】:How can I easily check in Python that all items in one list are included in the other list?如何在 Python 中轻松检查一个列表中的所有项目是否包含在另一个列表中?
【发布时间】:2021-04-25 02:04:22
【问题描述】:

我找到了一些解决方案,但没有一个是我需要的。

例如:

list1 = ['a', 'b', 'c']
list2 = ['a', 'a', 'b', 'c']

Counter(list1) == Counter(list2) -> True,但我需要 False 因为双 'a' //// set(list1) == set(list2) -> True,但我还需要False

我想编写一个小代码来从列表中搜索可能的单词。

示例:

wordCollection = ["dog", "go", "home", "long"] //// 输入字符:“NLGUCOBAD”

结果:狗,走,长

【问题讨论】:

    标签: python list function collections counter


    【解决方案1】:

    您可以将all 与一个简单的表达式结合使用:

    result = all((list1.count(x) == list2.count(x)) for x in list1)
    

    如果集合中的每个项目都是True,则all 返回True。当不是每个项目都是True 时,它也将返回False

    例如:

    all([True, True, True, True, True])
    >>> True
    
    all([True, False, True, True, True])
    >>> False
    

    考虑到这一点,您可以检查list1 中每个元素的计数是否与list2 中的相同。这就是list1.count(x) == list2.count(x) 的来源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      • 2014-06-25
      • 1970-01-01
      相关资源
      最近更新 更多