【问题标题】:IndexError: list assignment index out of range - pythonIndexError:列表分配索引超出范围 - python
【发布时间】:2018-10-21 19:51:21
【问题描述】:

我的代码有问题,我只想将结果写入 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

我该怎么办?

【问题讨论】:

  • 这条线是做什么的seleksi[0] = p.select() ?

标签: python python-2.7


【解决方案1】:

[],在后台调用__get(index)。当您说seleksi[0] 时,您正试图在seleksi 的索引0 处获取值,这是一个空列表。

你应该这样做:

seleksi = p.select()

【讨论】:

    【解决方案2】:

    当您使用

    初始化列表时
    seleksi = []
    

    这是一个空列表。列表的长度为 0。 因此

    seleksi[0] 
    

    给出一个错误。

    您需要附加到列表以获取值,例如

    seleksi.append(p.select())
    

    如果您仍想根据索引分配它,请将其初始化为零数组或一些虚拟值

    seleksi = [0]* n
    

    看到这个:List of zeros in python

    【讨论】:

      【解决方案3】:

      您在分配 seleksi[0] = p.select() 之前正在访问,这应该可以解决它:

      seleksi.append(p.select())
      

      由于您正在迭代 saleksi,我猜您真正想要的是存储 p.select(),因此您可能想要改为使用 seleksi = p.select()。

      编辑:

      我得到了这个 selections.writerow(selections) _csv.Error: sequence 预计

      你想写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)
      

      【讨论】:

      • 我得到了这个selections.writerow(selections) _csv.Error: sequence expected@Netwave
      • @RozBarb,我想你想写x,所以selections.writerow(x)
      • 当我添加这样的代码 seleksi.append(p.select()) with open('test.csv','wb') as selection: selections = csv.writer(selection) for x in seleksi: selections.writerow(x) 它只是写 index[0] @Netwave
      猜你喜欢
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2022-11-27
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多