【问题标题】:Comparing 2 lists of items and raising error if not in [closed]比较 2 个项目列表,如果不在 [关闭] 中则引发错误
【发布时间】:2020-12-21 11:19:08
【问题描述】:

我有 2 个需要比较的字符串列表。

list1["a", "b", "c", "d"]list2["a", "b", "c", "d", "e", "f"] 我已经成功地将它们与

check = any(i in ccourt for i in champs)
print(check) 

编辑:好的,所以我问得不好并且误解了any() 方法,对不起,我坚持的是比较部分。 是的,any() 部分有效,但并不是说list2"e""f" 不在list1 中,这就是我想要它做的事情。

提前谢谢你

【问题讨论】:

  • if not check?
  • 请从tour 重复on topicHow to Ask。 “教我这个基本的语言功能”对于 Stack Overflow 来说是题外话。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 无意取代现有的教程和文档。
  • 查看this 帖子了解如何在 Python 中引发异常。

标签: python list try-catch except


【解决方案1】:

您可以使用“设置”:

set(list2) - set(list1)

结果:

set(['e', 'f']) # 打印输出

set.difference 也可以。

set(list1).difference(list2)

【讨论】:

    【解决方案2】:
    lst1 = ["a", "b", "c", "d"]
    
    list2 = ["a", "b", "c", "d", "e", "f"]
    
    for i in list2:
        if i not in lst1:
            print(i, 'is not in lst1')
    
    >>> e is not in lst1
    >>> f is not in lst1
    
    

    map:

    list(map(lambda i: print(i, 'is not in lst1') if i not in lst1 else None, list2))
    
    >>> e is not in lst1
    >>> f is not in lst1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多