【问题标题】:Python: Need to remove first item from list then populate a wx.CheckListBoxPython:需要从列表中删除第一项,然后填充 wx.CheckListBox
【发布时间】:2015-06-12 05:07:03
【问题描述】:

我目前正在编写一个 python 脚本来分析 SNMP 数据。我有一个读取 csv 文件并在 CheckListBox 中组织的 CheckBoxes 中显示标题的函数。我想删除第一项,但这样做会导致我的 CheckListBox 不会填充,我无法弄清楚原因。代码如下:

#Generates CheckBoxList with fields from csv (first row)
def onSNMPGen(self,e):
    #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths -- fix later
    listItems = []
    print "*** Reading in ", self.snmpPaths[0], "....."
    with open(self.snmpPaths[0], 'r') as f: #remember to close csv
        reader = csv.reader(f)
        print "*** Populating Fields ..... "
        for row in reader:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)
            break
        f.close()
    #Need to remove 'Time' (first item) from listItems
    #listItems.pop(0) # this makes it so my CheckListBox does not populate
    #del listItems[0] # this makes it so my CheckListBox does not populate
    for key in listItems:
        self.SNMPCheckListBox.InsertItems(key,0)

【问题讨论】:

    标签: python list checklistbox


    【解决方案1】:

    感谢 roxan,我在看到错误后能够解决我的问题。我将 csv 行存储为列表中的一个项目,而不是将行的每一列作为一个项目。这是我的解决方法:

    #Generates CheckBoxList with fields from csv (first row)
    def onSNMPGen(self,e):
        #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths -- fix later
        listItems = []
        print "*** Reading in ", self.snmpPaths[0], "....."
        with open(self.snmpPaths[0], 'r') as f: #remember to close csv
            reader = csv.reader(f)
            print "*** Populating Fields ..... "
            for row in reader:
                listItems = row             break
            f.close()
        del listItems[0] #Time is always first item so this removes it
        self.SNMPCheckListBox.InsertItems(listItems,0)
    

    【讨论】:

      【解决方案2】:
       for row in reader:
                  #Inserts each field into CheckListBox as an item;
                  #self.SNMPCheckListBox.InsertItems(row,0)
                  listItems.append(row)
                  break
      

      因为您使用了 break,所以您的列表将只有一项。因此,当您删除该项目时,您的 CheckListBox 中没有任何内容可以填充。

      如果你 100% 确定它是第一项,那么你可以像这样重写你的循环:

       for row in reader[1:]:
                  #Inserts each field into CheckListBox as an item;
                  #self.SNMPCheckListBox.InsertItems(row,0)
                  listItems.append(row)
      

      reader[1:] 表示您只会在 listItems 列表中添加第二个项目。

      【讨论】:

      • 好的,我现在明白了。我的脚本其余部分的工作方式,该修复将导致其他问题。也许我想解析列表中的一个项目并以这种方式删除它,或者找到一种方法来忽略/删除 csv 文件的第一列
      • 感谢您指出我将 csv 行存储为一个项目,而不是多个项目。我想出了一个我将发布的修复程序
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2016-03-10
      相关资源
      最近更新 更多