【问题标题】:Is there a short contains function for lists?列表是否有简短的包含功能?
【发布时间】:2026-01-10 20:40:01
【问题描述】:

我看到人们正在使用any 来收集另一个列表以查看列表中是否存在某个项目,但是有没有一种快速的方法来做这样的事情?

if list.contains(myItem):
    # do something

【问题讨论】:

  • 你的问题暗示你只对list contains item感兴趣,而不是list contains sublist? /tuple/set/frozenset/...?

标签: python list search collections contains


【解决方案1】:

您可以使用以下语法:

if myItem in some_list:
    # do something

还有,逆运算符:

if myItem not in some_list:
    # do something

它适用于列表、元组、集合和字典(检查键)。

注意,这在列表和元组中是 O(n) 操作,但在集合和字典中是 O(1) 操作。

【讨论】:

  • 使用包含 numpy 数组的列表,这会检查 numpy 实例或 numpy 实例中的值吗?
  • 当心!这很匹配,而这很可能是您没想到的:o='--skip'; o in ("--skip-ias"); # returns True !
  • @AlexF: 匹配是因为("--skip-ias") 不是一个元组,而是一个字符串(括号什么都不做,就像(1) 只是一个整数)。如果你想要一个 1 元组,你需要在单个项目之后添加一个逗号:("--skip-ias",)(或(1,))。
  • 请注意,如果您在比较字符,则不区分大小写。
【解决方案2】:

还有另一种方法使用index。但我不确定这是否有任何问题。

list = [5,4,3,1]
try:
    list.index(2)
    #code for when item is expected to be in the list
    print("present")
except:
    #code for when item is not expected to be in the list
    print("not present")

输出:

不存在

【讨论】:

  • 它在 O(N) 时间内运行,并且 try-except 比 if 检查慢
【解决方案3】:

还有list方法:

[2, 51, 6, 8, 3].__contains__(8)
# Out[33]: True
[2, 51, 6, 3].__contains__(8)
# Out[33]: False

【讨论】:

    【解决方案4】:

    我最近想出了这个衬垫,如果列表包含任意数量的项目,则获取True,如果列表不包含任何事件或根本不包含任何事件,则获取False。使用 next(...) 会为其提供默认返回值 (False),这意味着它的运行速度应该比运行整个列表理解要快得多。

    list_does_contain = next((True for item in list_to_test if item == test_item), False)

    【讨论】:

    • 在我的例子中,我有一个名为 Category 的对象列表,并且需要它来测试属性 Link,所以这个解决方案更适合我的例子。谢谢
    • any(item == test_item for item in list_to_test) 我想也可以吗?
    【解决方案5】:

    除了其他人所说的,您可能还想知道in 所做的是调用list.__contains__ 方法,您可以在您编写的任何类上定义该方法,并且可以非常方便地使用python在他的全部范围内。

    一个愚蠢的用法可能是:

    >>> class ContainsEverything:
        def __init__(self):
            return None
        def __contains__(self, *elem, **k):
            return True
    
    
    >>> a = ContainsEverything()
    >>> 3 in a
    True
    >>> a in a
    True
    >>> False in a
    True
    >>> False not in a
    False
    >>>         
    

    【讨论】:

      【解决方案6】:

      如果项目不存在,列表方法index 将返回-1,如果存在则返回列表中项目的索引。或者,在 if 语句中,您可以执行以下操作:

      if myItem in list:
          #do things
      

      您还可以使用以下 if 语句检查元素是否不在列表中:

      if myItem not in list:
          #do things
      

      【讨论】:

      • 如果元素不存在,index 方法不会返回 -1,它会抛出 ValueError 异常。