user3141116
user3141116

Reputation: 23

Multiple selections from a list using Python

I have created a big list of server names. I want to present this as a menu to the user and create a new list that will contain only the names/multiple choices selected by the user.

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

When the user selects multiple choices from menu, the list I get is a list of numbers and not the actual server names to return. Also there is no error handling such as if the number is valid from menu or not.

Any help is appreciated, I am new to Python, trying to learn more.

Upvotes: 2

Views: 1690

Answers (3)

koslo
koslo

Reputation: 1

This returns/prints a list with the selected items from a QListWidget:

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()

Upvotes: 0

Preet Kukreti
Preet Kukreti

Reputation: 8607

Seeing as you havent had an answer yet, I will just give you an example of what i think you might be trying to achieve:

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

Upvotes: 1

Maxime Lorant
Maxime Lorant

Reputation: 36161

I guess you want to print each elements with an index next to it. The enumerate function returns an iterable object. This iterable object returns a tuple at each iteration, composed of an index (starting at 0) and the element at this index in your list.
Then, in the second time, you can loop over each index selected by the user and add the revelant element to a selected list.

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

Upvotes: 0

Related Questions