我想检查输入值是否等于列表中的值,而不是遍历列表中的每个值。
list=('a','b','c','d')
test=raw_input('enter letter')
if test in list:
if test == a:
(code)
if test == b:
(code)
if test == c:
(code)
if test == d:
(code)
请您参考如下方法:
这最好用字典来完成。
def a_code():
print "a"
def b_code():
print "b"
d={'a':a_code,'b':b_code}
test=raw_input("enter a or b")
d[test]()
当然,如果每种情况下的代码都相同,您可以这样做:
if test in ('a', 'b', 'c', 'd'): #tuple
do_something()
在功能上等同于:
if test in ['a', 'b', 'c', 'd']: #list slower than tuple -- ('a', 'b', 'c', 'd')
do_something()
或者,更简单地说:
if test in 'abcd': # string
do_something()
