【问题标题】:Python: Check if element is not in two lists?Python:检查元素是否不在两个列表中?
【发布时间】:2013-03-21 11:27:18
【问题描述】:

我需要检查一个元素是否不在两个列表中。我目前有:

if ele not in lista:
    if ele not in listb:
        do stuff

使用以下代码不起作用。有没有更有效的方式在 python 中完成上述操作?

if ele not in lista and listb:
    do stuff

【问题讨论】:

    标签: python list if-statement


    【解决方案1】:

    晚了,但我只是想添加一些更酷的东西

    假设两个列表长度相等

    a = [1,2,3,4,5]
    b = [6,7,8,9,10]
    c = all("h" not in pair for pair in zip(a,b))
    

    如果它们的长度不等:

    from itertools import zip_longest
    
    a = [1,2,3,4,5]
    b = [6,7,8,9,10,11,12,13]
    c = all("h" not in pair for pair in zip_longest(a,b))
    

    【讨论】:

      【解决方案2】:
      if ele not in lista and ele not in listb:
          # do stuff
      

      if ele not in lista + listb:
          # do stuff
      

      但第二个选项将涉及列表连接,这可能会导致大型列表出现内存问题,而且它必须通过列表两次。要解决此问题,您可以使用itertools:

      from itertools import chain
      if ele not in chain(lista, listb):
          # do stuff
      

      如果您要不断检查成员资格,您希望使用set,它具有O(1)(摊销)查找而不是O(n) 查找列表。

      例如。

      items_set = set(chain(lista, listb))
      if ele in items_set:  # this membership check will be a lot faster
          # do stuff
      

      【讨论】:

      • 我尝试了“不在和”但没有成功。我会试试'+'
      • @user2084666 您是否逐字尝试了第一个选项?你写的,if ele not in lista and listb,实际上是错误的,而是应用了 Python 的布尔逻辑,如果你愿意,你可以研究一下,但我写的方式确实有效
      【解决方案3】:
      if ele not in lista and ele not in listb:
      

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 2021-06-28
        相关资源
        最近更新 更多