根据列表内容验证用户输入的最佳方法是什么?

2024-05-22 00:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这里几乎是一个Python新手,正在努力学习。我有一个同事启动的脚本,我正在为它添加新功能。我想验证用户输入是否在我的两个列表中的一个列表中。你知道吗

我有一个用户的原始输入,要求输入站点名称,我想添加代码,检查用户的输入是否在预定义的列表sites\u 2017和sites\u 2018(稍后在代码中使用)中,如果不在,则返回一个错误,如果在,则继续脚本的其余部分。我到处搜索,看到了很多不同的while循环答案和函数,但到目前为止还没有一个引用多个列表来匹配。你知道吗

我只是想弄清楚最好的代码,以及while循环等在当前代码中的位置。你知道吗

# Ask user input for what they'd like to do? Render or audit? _Step user through process_

import os
import subprocess

getuser = raw_input("Please enter your username :")

print("1. render_device")
print("2. audit_deivce")
askuser = raw_input("Would you like to render_device or audit_deivce? : ")

#Render:

if askuser == "1":
        get_site_name = raw_input("Please enter the site name you'd like to render :")

        sites_2017 = ["bob", "joe", "charlie"]
        sites_2018 = ["sarah", "kelly", "christine"]

Tags: orto代码用户脚本列表inputraw
2条回答

在python中,可以使用成员资格测试操作符in。因此,不必使用循环进行检查,您可以组合列表并检查成员身份,如下所示:

if get_site_name in sites_2017 + sites_2018:

更新以处理评论

您需要在这里利用in,最好从注释中@abarnert提到的两个列表中创建一个集合。如果条件不满足,您可以将其包装到函数中并递归调用该函数(注意,为了与python3兼容,我将raw_input()更改为input()):

getuser = input("Please enter your username :")

print("1. render_device")
print("2. audit_device")

askuser = input("Would you like to render_device or audit_device? : ")

def verify_input(sites_set):

    get_site_name = input("Please enter the site name you'd like to render :")

    if get_site_name in sites_set:
        print('Proceed')
        return
    else:
        print('Not in either list!')
        verify_input(sites_set)

if askuser == "1":

        sites_2017 = ["bob", "joe", "charlie"]
        sites_2018 = ["sarah", "kelly", "christine"]

        verify_input(set(sites_2017 + sites_2018))

编辑

但是,更简单的实现是只使用while循环:

getuser = input("Please enter your username :")

print("1. render_device")
print("2. audit_device")

askuser = input("Would you like to render_device or audit_device? : ")

if askuser == "1":

        sites_2017 = ["bob", "joe", "charlie"]
        sites_2018 = ["sarah", "kelly", "christine"]

        sites_set = set(sites_2017 + sites_2018)
        proceed = False

        while not proceed:

            get_site_name = input("Please enter the site name you'd like to render :")

            if get_site_name in sites_set:
                print('Proceed')
                proceed = True
            else:
                print('Not in either list!')

相关问题 更多 >