简体   繁体   English

将其引用到列表时,是否可以快速检查python中的值是否等于另一个?

[英]Is it possible to check if a value is equal to another in python quickly when referring it to a list?

I want to check if an input value is equal a value inside the list without going through every value inside the list. 我想检查输入值是否等于列表内的一个值,而无需遍历列表内的每个值。

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)

This is better done with a dictionary. 最好用字典来完成。

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]()

Of course, if code is the same in each case, you could do: 当然,如果每种情况下的代码都相同,则可以执行以下操作:

if test in ('a', 'b', 'c', 'd'): #tuple
   do_something()

which is functionally equivalent to: 在功能上等效于:

if test in ['a', 'b', 'c', 'd']: #list slower than tuple -- ('a', 'b', 'c', 'd')
   do_something()

or, more simply: 或者,更简单地说:

if test in 'abcd': # string
   do_something()

This is really a tuple not a list. 这确实是一个元组而不是列表。 But yes, you can use the in membership test for this. 但是,可以的,您可以使用in成员资格测试。

With a tuple : tuple

In [1]: mtuple=('a','b','c','d')

In [2]: 'a' in mtuple
Out[2]: True

In [3]: 'z' in mtuple
Out[3]: False

Works the same with a list too: 同样适用于list

In [4]: mlist=['a','b','c','d']

In [5]: 'a' in mlist
Out[5]: True

In [6]: 'z' in mlist
Out[6]: False

More on the membership test with in toward the bottom of the page: 更多关于会员试验与朝着页面的底部:

The operators in and not in test for collection membership. 处于运营状态且未进行测试的集合成员身份的运营商。 x in s evaluates to true if x is a member of the collection s, and false otherwise. 如果x是集合s的成员,则x in s的评估结果为true,否则为false。 x not in s returns the negation of x in s. x not in s返回x in s的取反。 The collection membership test has traditionally been bound to sequences; 收集成员资格测试传统上是绑定到序列的; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. 如果该对象是一个序列,并且包含与该对象相等的元素,则该对象是该集合的成员。 However, it make sense for many other object types to support membership tests without being a sequence. 但是,对于许多其他对象类型来说,无需顺序即可支持成员资格测试是有意义的。 In particular, dictionaries (for keys) and sets support membership testing. 特别是,字典(用于键)和集合支持成员资格测试。

You can easily find the index of the matching item using the index method of sequences: 您可以使用序列的index方法轻松找到匹配项的index

choices=('a','b','c','d')
test=raw_input('enter letter: ')
if test in choices:
    index = choices.index(test)
    # do something based on index

(I changed the name of the variable named list in your sample code to choices because list is the predefined name of a fundamental type in Python -- besides that, the variable actually contains a tuple of values, not a list of them because they're enclosed in parentheses instead of square brackets.) (我将示例代码中名为list的变量的名称更改为choices因为list是Python中基本类型的预定义名称-除此之外,该变量实际上包含值的元组,而不是它们的列表,因为它们是括在括号中而不是方括号中。)

The if test in choices: tells you quickly if the value assigned to test is equal to any of those in choices . if test in choices:if test in choices:迅速告诉您分配给test的值是否等于choices任何一个。 The index() method does essentially the same thing but also tells you the index of which one. index()方法本质上是相同的,但是还会告诉您哪个索引。 One important difference between them is that when the value isn't in the sequence, the index() method will throw a ValueError , whereas the in operator will just return False if there's no match. 它们之间的一个重要区别是,当值不在序列中时, index()方法将抛出ValueError ,而in运算符将在没有匹配项的情况下仅返回False

Since they're so similar, it's uncommon (as well as inefficient) to use them both as shown. 由于它们是如此相似,因此如图所示同时使用它们并不常见(效率低下)。

From the rest of your code it looks like perhaps what you really wanted to know is a good way of dispatching based on the value of test . 从代码的其余部分来看,您似乎真正想知道的是一种基于test值进行分派的好方法。 As many of the other answers indicate, this is often done with a dictionary in Python since it has no switch or case: statement found in other programming languages. 正如许多其他答案所表明的那样,这通常是用Python中的字典来完成的,因为它没有switchcase:在其他编程语言中找到的语句。

To add to the other examples, here's a somewhat novel way to build and use one (a dictionary) on-the-fly: 除了其他示例外,这是一种动态构建和使用(字典)的新颖方法:

def func_a(): pass
def func_b(): pass
def func_c(): pass
def func_d(): pass

test = raw_input('enter letter: ')
try:
    {'a': func_a,
     'b': func_b,
     'c': func_c,
     'd': func_d,
    }[test]()  # call corresponding function
except KeyError:
    # handle other values of test
    ...

Another alternative, since the names of the func_x 's defined are all global variables, which allows you to avoid even having to build your own dictionary, would be to just use the one returned by the built-in globals() function instead: 另一个替代方法是,由于func_x的定义名称都是全局变量,因此您甚至不必构建自己的字典,就可以使用内置的globals()函数返回的globals()代替:

test = raw_input('enter letter: ')
try:
    globals()['func_'+test]()  # call appropriately named function
except KeyError:
    # handle illegal values of test
    ...

Were you thinking of something like this perhaps? 您是否正在考虑这样的事情?

def block_a():
    print "AAA"

def block_b():
    print "BBB"

def block_c():
    print "CCC"

d = {"A": block_a, "B" : block_b, "C" : block_c}

test=raw_input('enter letter: ')

d[test]()

While you can do things with dictionaries to emulate a switch statement, for only a few items (4 in this case), there's nothing wrong with using if statements 尽管您可以使用字典来模拟switch语句,但是仅执行少数几个项目(本例中为4),但是使用if语句并没有错

You could use the elif statement (short for "else if"), to make it clear only one of the branches will be executed (eg if it matches "a", there's no point checking c, and d). 您可以使用elif语句(“ else if”的缩写)来表明只有一个分支将被执行(例如,如果它匹配“ a”,则没有检查c和d的点)。

Also the initial if test in mylist: check seemed redundant in your example code 也是if test in mylist:的初始if test in mylist:检查在您的示例代码中似乎是多余的

So it can be simplified to: 因此可以简化为:

things=('a','b','c','d')
test=raw_input('enter letter')

if test == "a":
    code("was called with 'a'!")
elif test == "b":
    code("was called with 'b'!")
elif test == "c":
    code("was called with 'c'!")
elif test == "d":
    code("was called with 'd'!")
else:
    # Optional else block, executed if the input wasn't a, b, c or d
    print "Uhoh"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM