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

delete items from 3 different lists

我需要一些帮助,以便在单击按钮时同时从某些列表中删除某些项目。

这是代码:

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 中删除项目。

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

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

 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),但是如果值不存在会抛出异常

Python 列表有一个 "remove" 对象直接执行该操作:

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