如何让用户从有限列表中选择输入?

Gia*_*dro 4 python multiple-choice

我是python和编程的新手,所以如果这是一个"noob问题",我很抱歉.无论如何,是否可以在python中选择多项选择,而不使用if循环?

愚蠢的例子:

print "Do you want to enter the door"
raw_input ("Yes or not")
Run Code Online (Sandbox Code Playgroud)

并且用户只能在选择之间进行选择.

Kho*_*opa 12

如果您需要定期执行此操作,可以使用方便的库来帮助您轻松获得更好的用户体验:查询者

免责声明:据我所知,如果没有一些黑客攻击,它将无法在Windows上运行.

您可以使用pip安装inquirer:

pip install inquirer
Run Code Online (Sandbox Code Playgroud)

示例1:多个选择

查询者的一个功能是让用户从带有键盘箭头键的列表中进行选择,而不是要求他们写出答案.这样,您可以为控制台应用程序实现更好的UX.

以下是从文档中获取的示例:

import inquirer
questions = [
  inquirer.List('size',
                message="What size do you need?",
                choices=['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
            ),
]
answers = inquirer.prompt(questions)
print answers["size"]
Run Code Online (Sandbox Code Playgroud)

询问者的例子

示例2:是/否问题:

对于诸如你的"是/否"问题,你甚至可以使用询问者的确认:

import inquirer
confirm = {
    inquirer.Confirm('confirmed',
                     message="Do you want to enter the door ?" ,
                     default=True),
}
confirmation = inquirer.prompt(confirm)
print confirmation["confirmed"]
Run Code Online (Sandbox Code Playgroud)

是的,询问者没有问题

其他有用的链接:

询问者的Github回购

  • 对于Windows用户,请尝试使用`PyInquirer`。这是他们文档的链接:https://github.com/CITGuru/PyInquirer/ (2认同)

小智 9

对于仅选择“是”或“否”来说,这有点过分了,但它是一个通用解决方案,也适用于两个以上的选项。它对不存在的选项进行保护,并将强制用户提供新的有效输入。这没有任何进口。

首先是一个处理所有功能的函数:

def selectFromDict(options, name):
    index = 0
    indexValidList = []
    print('Select a ' + name + ':')
    for optionName in options:
        index = index + 1
        indexValidList.extend([options[optionName]])
        print(str(index) + ') ' + optionName)
    inputValid = False
    while not inputValid:
        inputRaw = input(name + ': ')
        inputNo = int(inputRaw) - 1
        if inputNo > -1 and inputNo < len(indexValidList):
            selected = indexValidList[inputNo]
            print('Selected ' +  name + ': ' + selected)
            inputValid = True
            break
        else:
            print('Please select a valid ' + name + ' number')
    return selected
Run Code Online (Sandbox Code Playgroud)

然后是一个包含所有选项的字典

options = {}
#     [USER OPTION] = PROGRAM RESULT
options['Yes'] = 'yes'
options['No'] = 'no'
Run Code Online (Sandbox Code Playgroud)

然后使用选项调用该函数

# Let user select a month
option = selectFromDict(options, 'option')
Run Code Online (Sandbox Code Playgroud)

结果是:

> Select a option:
> 1) Yes
> 2) No
> option: 3
> Please select a valid option number
> option: 1
> Selected option: yes
Run Code Online (Sandbox Code Playgroud)

如前所述,这适用于例如一年中所有月份重新使用上述功能:

months = {}
months['January'] = 'jan'
months['February'] = 'feb'
months['March'] = 'mar'
months['April'] = 'apr'
months['May'] = 'may'
months['June'] = 'jun'
months['July'] = 'jul'
months['August'] = 'aug'
months['September'] = 'sep'
months['October'] = 'oct'
months['November'] = 'nov'
months['December'] = 'dec'

# Let user select a month
month = selectFromDict(months, 'Month')
Run Code Online (Sandbox Code Playgroud)

结果示例:

> Select a Month:
> 1) January
> 2) February
> 3) March
> 4) April
> 5) May
> 6) June
> 7) July
> 8) August
> 9) September
> 10) October
> 11) November
> 12) December
> Month: 5
> Selected Month: may
Run Code Online (Sandbox Code Playgroud)


hol*_*web 8

实现您所需要的一种可能的方法是使用循环while

print "Do you want to enter the door"
response = None
while response not in {"yes", "no"}:
    response = raw_input("Please enter yes or no: ")
# Now response is either "yes" or "no"
Run Code Online (Sandbox Code Playgroud)

  • 在两个元素的情况下,它几乎没有任何区别,但随着元素数量的增加,集合变得更快。其原因是“__contains__”方法的底层实现,该方法对于列表会迭代每个元素,直到找到匹配项或耗尽所有元素。对于集合,散列技术用于提供几乎恒定的执行时间,而不管元素的数量如何。 (3认同)

M.V*_*lee 8

对于使用提示工具包 2 或 3 的与操作系统无关的解决方案,请使用问题

https://github.com/tmbo/questionary