检查 Python 中的列表中是否有(不)某些内容 [英] Check if something is (not) in a list in Python

查看:22
本文介绍了检查 Python 中的列表中是否有(不)某些内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

if curr_x -1 >0 和 (curr_x-1 , curr_y) 不在 myList 中:# 做点什么

虽然这对我来说并不真正有效.我做错了什么?

解决方案

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

<预><代码>>>>3 不在 [2, 3, 4]错误的>>>3 不在 [4, 5, 6]真的

或者使用元组:

<预><代码>>>>(2, 3) 不在 [(2, 3), (5, 6), (9, 1)]错误的>>>(2, 3) 不在 [(2, 7), (7, 3), "hi"]真的

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

Or with tuples:

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

这篇关于检查 Python 中的列表中是否有(不)某些内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆