Skip to main content
 首页 » 编程设计

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

2025年05月04日11jackei

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

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