有没有办法检查一个项目是否存在于 Python 元组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14902997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to check if an item exists in a Python tuple?
提问by Joan Venge
I have seen an indexfunction but it says it errors out if it can't find it. Is there a simple way to just check if the item exists? I just want to get a boolean value of the result so like:
我见过一个index函数,但它说如果找不到它就会出错。有没有一种简单的方法来检查项目是否存在?我只想获得结果的布尔值,例如:
if tuple.exists("item"):
print "it exists"
采纳答案by Rohit Jain
Use inoperator:
使用in运算符:
>>> 2 in (2, 3, 4)
True
inoperator can be used to check for the membership of any element in a sequence.
in运算符可用于检查序列中任何元素的成员资格。
And don't name your tuple as tuple. Use a different name.
并且不要将您的元组命名为tuple. 使用不同的名称。

