从3个不同的列表中删除项目

时间:2016-02-01 12:53:42

标签: python list pyqt qlistwidget

当点击一个按钮时,我需要帮助同时删除某些列表中的某些项目。

这是代码:

class Window(QMainWindow):
  list_1 = []  #The items are strings
  list_2 = []  #The items are strings

  def __init__(self):
    #A lot of stuff in here

  def fillLists(self):
    #I fill the lists list_1 and list_2 with this method

  def callAnotherClass(self):
    self.AnotherClass().exec_()   #I do this to open a QDialog in a new window

class AnotherClass(QDialog):
  def __init__(self):
    QDialog.__init__(self)

    self.listWidget = QListWidget()

  def fillListWidget(self):
    #I fill self.listWidget in here

  def deleteItems(self):
    item_index = self.listWidget.currentRow()
    item_selected = self.listWidget.currentItem().text()
    for i in Window.list_2:
      if i == item_selected:
        ?????????? #Here is where i get confussed

当我使用组合键打开QDialog时,我会在QListWidget中看到一些项目。在deleteItems方法中,我从QListWidget中选择的项目中获取索引和文本。这很好。

当我按下按钮(我已经创建)时,我需要做的是从list_1list_2QListWidget删除该项目。

我该怎么做?希望你能帮帮我。

2 个答案:

答案 0 :(得分:1)

如果你有值,那么只需在每个列表中找到它的索引然后删除它。类似的东西:

 item_selected = self.listWidget.currentItem().text()
 i = Window.list_2.index(item_selected)
 if i >= 0: 
    del Window.list_2[i]

您也可以直接使用Widow.list_x.remove(value)但如果该值不存在则会抛出异常。

答案 1 :(得分:1)

Python列表有"删除"直接执行该操作的对象:

Window.list_2.remove(item_selected)  

(不需要你的for循环)

如果您需要对列表项执行更复杂的操作,则可以使用index方法检索项目索引:

position = Window.list_2.index(item_selected)
Window.list_2[position] += "(selected)"

在某些情况下,您需要执行for循环以获取实际索引,以及列表或其他序列的索引处的内容。在这种情况下,请使用内置enumerate

使用枚举模式(如果remove不存在)将如下所示:

for index, content in enumerate(Window.list_2):
  if content == item_selected:
      del Window.list_2[index]
      # must break out of the for loop,
      # as the original list now has changed: 
      break