Python:需要从列表中删除第一项然后填充wx.CheckListBox

时间:2015-04-07 14:42:41

标签: python list checklistbox

我目前正在研究一个用于分析SNMP数据的python脚本。我有一个函数,它读入一个csv文件,并在CheckBoxBox中组织的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)

2 个答案:

答案 0 :(得分:0)

 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列表中添加第二项。

答案 1 :(得分:0)

感谢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)