针对 Python 中的列表测试用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3944655/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:28:08  来源:igfitidea点击:

Testing user input against a list in python

python

提问by Guillermo Siliceo Trueba

I need to test if the user input is the same as an element of a list, right now I'm doing this:

我需要测试用户输入是否与列表元素相同,现在我正在这样做:

cars = ("red", "yellow", "blue")
guess = str(input())

if guess == cars[1] or guess == cars[2]:
        print("success!")

But I'm working with bigger lists and my if statement is growing a lot with all those checks, is there a way to reference multiple indexes something like:

但是我正在处理更大的列表,并且我的 if 语句在所有这些检查中都增长了很多,有没有办法引用多个索引,例如:

if guess == cars[1] or cars[2]

or

或者

if guess == cars[1,2,3]

Reading the lists docs I saw that it's impossible to reference more than one index like, I tried above and of course that sends a syntax error.

阅读列表文档我看到不可能引用多个索引,我在上面尝试过,当然这会发送语法错误。

采纳答案by RichieHindle

The simplest way is:

最简单的方法是:

if guess in cars:
    ...

but if your list was huge, that would be slow. You should then store your list of cars in a set:

但如果你的清单很大,那会很慢。然后,您应该将汽车列表存储在一个集合中:

cars_set = set(cars)
....
if guess in cars_set:
    ...

Checking whether something is present is a set is much quicker than checking whether it's in a list (but this only becomes an issue when you have many many items, and you're doing the check several times.)

检查某个东西是否存在是一个集合比检查它是否在一个列表中要快得多(但这只会在你有很多很多项目并且你要进行多次检查时才会成为问题。)

(Edit: I'm assuming that the omission of cars[0]from the code in the question is an accident. If it isn't, then use cars[1:]instead of cars.)

(编辑:我假设cars[0]问题中代码的遗漏是意外。如果不是,则使用cars[1:]代替cars。)

回答by unutbu

Use guess in carsto test if guessis equal to an element in cars:

使用guess in cars测试是否guess等于在一个元素cars

cars = ("red","yellow","blue")
guess = str(input())

if guess in cars:
        print ("success!")

回答by poke

Use in:

使用in

if guess in cars:
    print( 'success!' )

See also the possible operations on sequence type as documented in the official documentation.

另请参阅官方文档中记录的对序列类型的可能操作。

回答by bdk

@Sean Hobbs: First you'd have to assign a value to the variable index.

@Sean Hobbs:首先,您必须为变量索引分配一个值。

index = 0

You might want to use while True to create the infinite loop, so your code would be like this:

您可能希望使用 while True 来创建无限循环,因此您的代码将如下所示:

while True:

    champ = input("Guess a champion: ")
    champ = str(champ)

    found_champ = False
    for i in listC:
        if champ == i:
            found_champ = True

    if found_champ:
        print("Correct")
    else:
        print("Incorrect")