Python 检查一个值是否等于数组中的任何值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18132912/
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
Checking if a value is equal to any value in an array
提问by ThaRemo
I'm new to python (and programming in general) and I can't seem to find a solution to this by myself. I want to check the first letter of a string is equal to any letter stored in an array, something like this:
我是 python 的新手(以及一般的编程),我自己似乎无法找到解决方案。我想检查字符串的第一个字母是否等于存储在数组中的任何字母,如下所示:
letter = ["a", "b", "c"]
word = raw_input('Enter a word:')
first = word[0]
if first == letter:
print "Yep"
else:
print "Nope"
But this doesn't work, does anyone know how it will? Thanks in advance!
但这不起作用,有谁知道它会如何?提前致谢!
采纳答案by Sukrit Kalra
You need to use the in
operator. Use if first in letter:
.
您需要使用in
运算符。使用if first in letter:
.
>>> letter = ["a", "b", "c"]
>>> word = raw_input('Enter a word:')
Enter a word:ant
>>> first = word[0]
>>> first in letter
True
And one False test,
还有一个错误的测试,
>>> word = raw_input('Enter a word:')
Enter a word:python
>>> first = word[0]
>>> first in letter
False
回答by Sukrit Kalra
Try using the in
keyword:
尝试使用in
关键字:
if first in letter:
On your current code, you are comparing a string character (first
which equals the first character in word
) to a list. So, let's say my input is "a word"
. What your code is actually doing is:
在您当前的代码中,您将一个字符串字符(first
等于 中的第一个字符word
)与一个列表进行比较。所以,假设我的输入是"a word"
. 你的代码实际上在做什么:
if "a" == ["a", "b", "c"]:
which will always be false.
这将永远是错误的。
Using the in
keyword however is doing:
in
然而,使用关键字正在做:
if "a" in ["a", "b", "c"]:
which tests whether "a"
is a member of ["a", "b", "c"]
and returns true in this case.
在这种情况下,它测试是否"a"
是 的成员["a", "b", "c"]
并返回 true。
回答by squiguy
回答by Brian H
The problem as I see it, is that you are asking does a character equal an array. This will always return false.
在我看来,问题在于您问的是一个字符是否等于一个数组。这将始终返回 false。
Try using a loop to check 'first' against each item in 'letter'. Let me know if you need help on figuring out how to do this.
尝试使用循环检查“信件”中的每个项目的“第一项”。如果您需要帮助了解如何执行此操作,请告诉我。