IndexError:列表赋值索引超出范围 - python

时间:2018-05-11 11:41:46

标签: python python-2.7

我的代码有问题,我只想在csv中写出结果,我得到IndexError

seleksi = []
p = FeatureSelection(fiturs, docs)

seleksi[0] = p.select()
with open('test.csv','wb') as selection:
    selections = csv.writer(selection)
    for x in seleksi:
        selections.writerow(selections)

在p.select中是:

['A',1]
['B',2]
['C',3]
etc

我收到了错误:

seleksi[0] = p.select()
IndexError: list assignment index out of range

Process finished with exit code 1

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您在seleksi[0] = p.select()转让之前正在访问,这应解决它:

seleksi.append(p.select())

由于您正在迭代saleksi,我猜您真正想要的是存储p.select(),您可能想要seleksi = p.select()而不是。{/ p>

修改

  

我得到了这个选择。写作(选择)_csv.Error:序列   预期

你想写x,所以selections.writerow(x)是你要走的路。

您的最终代码如下所示:

p = FeatureSelection(fiturs, docs)

seleksi = p.select()
with open('test.csv','wb') as selection:
    selections = csv.writer(selection)
    for x in seleksi:
        selections.writerow(x)