IndexError: list assignment index out of range - python
我的代码有问题,我只想把结果写成csv,我得到了
1 2 3 4 5 6 7 8 | 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.选择是:
1 2 3 4 | ['A',1] ['B',2] ['C',3] etc |
我在以下方面出错:
1 2 3 4 | seleksi[0] = p.select() IndexError: list assignment index out of range Process finished with exit code 1 |
我该怎么办?
你应该这样做:
1 | seleksi = p.select() |
初始化列表时使用
1 | seleksi = [] |
这是一个空列表。列表的长度为0。因此
1 | seleksi[0] |
给出一个错误。
您需要附加到列表中以获取值,比如
1 | seleksi.append(p.select()) |
如果仍要基于索引分配它,请将其初始化为零数组或某个虚拟值。
1 | seleksi = [0]* n |
参见:python中的零列表
您在执行
1 | seleksi.append(p.select()) |
既然您正在迭代
编辑:
i got this selections.writerow(selections) _csv.Error: sequence
expected
你想写
您的最终代码如下所示:
1 2 3 4 5 6 7 | 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) |