简体   繁体   中英

how to create a list from another list based on the sequence of checked item using python

How to make a new list from an existing listing based on the user selection example:

l1 = [1,2,3,4,5]

if the user check first the item 3 then check the item 2 the l2 = [3,2]

until now if the user check first the item 3 and then check the item 2 the l2 =[2,3]

my question is how to create a list based on the checked item .

code:

def loadFile(self):
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File", "", "CSV Files (*.csv)");
        self.lineEdit.setText(fileName)
        df = pd.read_csv(fileName)
        model = PandasModel(df)
        self.pandasTv.setModel(model)
        self.df = df

    #part that display items in the qlistWidget
        self.header_list.clear()
        savelist = list(self.df)
        for item in savelist:
            qitem = QtWidgets.QListWidgetItem ( ) 
            qitem.setText ( item ) 
            qitem.setCheckState ( QtCore.Qt.Unchecked ) 
            self.header_list.addItem ( qitem )
        
      
    def selectionChanged(self):
        checked = []
        for row in range(self.header_list.count()):
            item = self.header_list.item(row)
            if item.checkState():
                checked.append(item)
        print("Checked items: ", ", ".join(i.text() for i in checked))
        self.checked = [i.text() for i in checked]

Assuming the items are check boxes, you can use a list and check if the item is already added and then add if needed. This should give you the selection order.

checked = []
def selectionChanged(self):
    global checked
    for row in range(self.header_list.count()):
        item = self.header_list.item(row)
        if item.checkState():
            if not item in checked: checked.append(item) # add item if not already added
        else:
            if item in checked: del checked[item] # remove unchecked items
    print("Checked items: ", ", ".join(i.text() for i in checked))
    self.checked = [i.text() for i in checked]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM