检查 Python 列表中是否有(不)某些东西

2022-01-20 00:00:00 python list conditional membership

问题描述

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

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?


解决方案

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

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

或者使用元组:

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

相关文章