我创建了一个很大的服务器名称列表。我想将此作为菜单呈现给用户并创建一个新列表,该列表仅包含用户选择的名称/多个选项。
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的新手,试图了解更多信息。
答案 0 :(得分:1)
看到你还没有得到答案,我只想举例说明你认为你可能想要实现的目标:
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
答案 1 :(得分:0)
我想你想打印每个元素旁边有一个索引。 enumerate
function返回一个可迭代对象。这个可迭代对象在每次迭代时返回一个元组,由一个索引(从0开始)和列表中该索引处的元素组成。
然后,在第二次,您可以遍历用户选择的每个索引,并将revelant元素添加到selected
列表。
BigList = ['server1','server2','server3','server4']
# Show every index
for index, element in enumerate(BigList):
print "%d. %s" % (index, element)
print "%d. %s Return to main menu" % (i+1,BigList)
menu = raw_input("Enter the selection with comma:")
menu.split(",")
selected = []
for data in menu:
try:
index = int(data.strip())
selected.append(BigList[index])
except ValueError:
pass # Need to manage this case, where it's not an integer
return selected
答案 2 :(得分:0)
import sys
from PyQt5.QtWidgets import (QApplication, QGridLayout, QLabel, QWidget, QListWidget, QAbstractItemView, QMainWindow)
class Main(QMainWindow):
def __init__(self, parent = None):
QMainWindow.__init__(self,parent)
self.initUI()
def initUI(self):
self.setWindowTitle('Input dialog')
win=QWidget()
self.setCentralWidget(win)
mainLayout = QGridLayout()
self.std = QListWidget()
self.std.setSelectionMode(QAbstractItemView.MultiSelection)
self.std.addItems(["AB", "EF", "JK"])
self.std.itemClicked.connect(self.selectionchange)
self.stdl = QLabel(self)
self.stdl.setText('select')
mainLayout.addWidget(self.stdl, 0, 0)
mainLayout.addWidget(self.std, 0, 1)
win.setLayout(mainLayout)
win.show()
def selectionchange(self):
se=[]
for i in self.std.selectedItems():
m=i.text()
se.append(m)
print(se)
def main():
app = QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()