从3个不同的列表中删除项目 [英] delete items from 3 different lists

查看:95
本文介绍了从3个不同的列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单击按钮的同时,我需要一些帮助同时删除某些列表中的某些项目.

I need some help with deleting some items from some lists at the same time, when a button is clicked.

这是代码:

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中选择的项目中获取索引和文本.很好.

When i open the QDialog with a combination of keys, i see in the QListWidget some items. In the deleteItems method, i get the index and the text from the item that i selected in the QListWidget. That works fine.

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

What i need to do is to delete the item from the list_1, list_2, and the QListWidget when i press a button (that i have already created).

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

How can i do this? Hope you can help me.

推荐答案

Python列表具有一个删除"对象,可以直接执行该操作:

Python lists have a "remove" object that perform that action directly:

Window.list_2.remove(item_selected)  

(不需要for循环)

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

If you ever need to perform more complex operations on the list items, you can retrieve an item's index with the index method instead:

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

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

And in some ocasions you will want to do a for loop getting to the actual index, as well as the content at that index of a list or other sequence. In that case, use the builtin enumerate.

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

Using the enumerate pattern, (if removedid not exist) would look like:

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

这篇关于从3个不同的列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆