在Python中检查列表中是否有内容

2024-04-25 05:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中有一个元组列表,并且我有一个条件,只有当元组不在列表中时,我才想接受分支(如果它在列表中,那么我不想接受if分支)

if curr_x -1 > 0 and (curr_x-1 , curr_y) not in myList: 

    # Do Something

不过,这对我来说并不管用。我做错了什么?


Tags: andin列表if分支not条件do
2条回答

How do I check if something is (not) in a list in Python?

最便宜、最可读的解决方案是使用^{}运算符(或者在您的特定情况下,使用not in)。如文件所述

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

另外

The operator not in is defined to have the inverse true value of in.

y not in x在逻辑上与not y in x相同。

下面是几个例子:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

这也适用于元组,因为元组是散列的(因为它们也是不可变的):

(1, 2) in [(3, 4), (1, 2)]
#  True

如果RHS上的对象定义了^{}方法,in将在内部调用它,如文档Comparisons部分最后一段所述。

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in短路,因此如果元素位于列表的开头,in计算速度更快:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

如果您想做的不仅仅是检查列表中是否有项目,还可以选择:

  • list.index可用于检索项的索引。如果该元素不存在,则引发ValueError
  • list.count如果要计算出现次数,可以使用。

XY问题:你考虑过sets吗?

问自己以下问题:

  • 你需要不止一次检查一个项目是否在列表中?
  • 这个检查是在循环内完成的,还是在重复调用函数时完成的?
  • 你在列表中存储的项目是散列的吗?你能打电话给他们吗?

如果您对这些问题的回答是“是”,则应该使用set。对lists的in成员资格测试是O(n)时间复杂度。这意味着python必须对列表进行线性扫描,访问每个元素并将其与搜索项进行比较。如果重复执行此操作,或者如果列表很大,则此操作将产生开销。

set另一方面,对象散列它们的值以进行常量时间成员身份检查。检查也使用in完成:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

如果不幸的是,您正在搜索/未搜索的元素位于列表的末尾,python将一直扫描到列表的末尾。从下面的计时可以明显看出这一点:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

提醒一下,只要您正在存储和查找的元素是散列的,那么这是一个合适的选项。总之,它们要么是不可变的类型,要么是实现__hash__的对象。

错误可能在代码的其他地方,因为它应该工作正常:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

或使用元组:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

相关问题 更多 >