针对 Python 中的列表测试用户输入 [英] Testing user input against a list in python

查看:39
本文介绍了针对 Python 中的列表测试用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!")

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

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 guess == cars[1] or cars[2]

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.

推荐答案

最简单的方法是:

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.)

(我假设问题代码中 cars[0] 的遗漏是一个意外.如果不是,则使用 cars[1:] 而不是 cars.)

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

这篇关于针对 Python 中的列表测试用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆