问题:检查Python列表中是否有东西

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

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

    # Do Something

不过,这对我来说并不是很有效。我做错了什么?

I have a list of tuples in Python, and I have a conditional where I want to take the branch ONLY if the tuple is not in the list (if it is in the list, then I don’t want to take the if branch)

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

    # Do Something

This is not really working for me though. What have I done wrong?


回答 0

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

>>> 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

The bug is probably somewhere else in your code, because it should work fine:

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

Or with tuples:

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

回答 1

如何检查Python列表中是否包含某些内容?

最便宜,最易读的解决方案是使用运算符(或在您的特定情况下为not in)。如文档中所述,

运营商innot in进行会员资格测试。x in s评估 True是否x为的成员sFalse否则为。x not in s返回的否定x in s

另外,

运算符not in被定义为具有的反真值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则将在内部调用该方法,如文档“ 比较”部分的最后一段所述。

innot in,由可迭代或实现该__contains__()方法的类型支持 。例如,您可以(但不应)这样做:

[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则引发a。
  • list.count 如果您要计算发生次数,可以使用。

XY问题:您考虑过sets吗?

问自己以下问题:

  • 您是否需要检查一个项目是否在列表中多次?
  • 该检查是在循环内完成还是要重复调用一个函数?
  • 您存储在列表中的项目是否可哈希化?IOW,你可以打电话hash给他们吗?

如果您对这些问题的回答为“是”,则应改用“ a” set。s 的in隶属度检验list是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)

提醒一下,这是一个合适的选项,只要要存储和查找的元素是可哈希的即可。IOW,它们要么必须是不可变的类型,要么是必须实现的对象__hash__

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

The cheapest and most readable solution is using the operator (or in your specific case, not in). As mentioned in the documentation,

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.

Additionally,

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

y not in x is logically the same as not y in x.

Here are a few examples:

'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

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

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

If the object on the RHS defines a method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

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 short-circuits, so if your element is at the start of the list, in evaluates faster:

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)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you’re storing on your list hashable? IOW, can you call hash on them?

If you answered “yes” to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you’re doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

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

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

If you’re unfortunate enough that the element you’re searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

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)

As a reminder, this is a suitable option as long as the elements you’re storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。