gpt4 book ai didi

python - 使用 Python 从列表中进行多项选择

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:59 26 4
gpt4 key购买 nike

我已经创建了一个很大的服务器名称列表。我想将其作为菜单呈现给用户,并创建一个新列表,其中仅包含用户选择的名称/多个选项。

BigList = ['server1','server2','server3','server4']
while (i < len(BigList)):
i =+ 1
print "%d. %s Return to main menu" % (i+1,BigList)
menu = raw_input("Enter the selection with comma:")
menu = menu.split(",")
return menu

当用户从菜单中选择多个选项时,我得到的列表是一个数字列表,而不是要返回的实际服务器名称。也没有错误处理,例如菜单中的数字是否有效。

感谢任何帮助,我是 Python 的新手,正在尝试学习更多。

最佳答案

鉴于您还没有得到答案,我将仅举一个我认为您可能想要实现的目标的示例:

BigList = ['server1','server2','server3','server4']

# here we use enumerate to generate the index i for the current item
# we pass in a temp list with an extra entry concatenated so that we
# dont need to duplicate the print expression
input_list = BigList + ['Return to main menu']
for i, item in enumerate(input_list):
print "%d. %s" % (i, item)

# get user input
menu_input = raw_input("Enter the selection with comma:")

# the list of selection indexes
menu_selection_indexes = []

# sanitize and store the indexes from user input string
for i in menu_input.split(','):
# could print/throw errors on bad input
# here we choose to discard bad list items silently
try:
# convert the string e.g. "2" into an integer type
# so that we can use it to index into our menu list
val = int(i.strip())
except ValueError, ve:
# some strings (e.g. "a") cannot be converted to an integer
# a ValueError exception is thrown if this is attempted
# we catch this exception and just ignore this value,
# skipping this value continuing on with the next for-loop item
continue
# ignore indexes that exceeed the acceptable input list size
if val > len(input_list):
continue
menu_selection_indexes.append(val)

# print indexes
print menu_selection_indexes

# if the last possible input index was chosen, we return to menu
if len(BigList) in menu_selection_indexes:
if not len(menu_selection_indexes) == 1:
print "warning: mixed commands"
print "will return to main menu"

else:
# list of items selected, using list comprehensions
menu_selection_names = [input_list[i] for i in menu_selection_indexes]

# print names
print menu_selection_names

关于python - 使用 Python 从列表中进行多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com