0

I have a problem with my code, I just want to write the result in csv and i got 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)

In p.select is:

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

and i got error in:

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

Process finished with exit code 1

what should i do?

akshat
  • 1,219
  • 1
  • 8
  • 24
RozBarb
  • 9
  • 2

3 Answers3

1

[], calls __get(index) in background. when you say seleksi[0], you are trying to get value at index 0 of seleksi, which is an empty list.

You should just do:

seleksi = p.select()
akshat
  • 1,219
  • 1
  • 8
  • 24
0

You are accesing before assignment on seleksi[0] = p.select(), this should solve it:

seleksi.append(p.select())

Since you are iterating over saleksi I guess that what you really want is to store p.select(), you may want to do seleksi = p.select() instead then.

EDIT:

i got this selections.writerow(selections) _csv.Error: sequence expected

you want to write x, so selections.writerow(x) is the way to go.

Your final code would look like this:

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)
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • and i got this `selections.writerow(selections) _csv.Error: sequence expected` @Netwave – RozBarb May 11 '18 at 11:46
  • @RozBarb, i think you want to write `x`, so `selections.writerow(x)` – Netwave May 11 '18 at 11:48
  • when i add the code like this `seleksi.append(p.select()) with open('test.csv','wb') as selection: selections = csv.writer(selection) for x in seleksi: selections.writerow(x)` it's just write index[0] @Netwave – RozBarb May 11 '18 at 12:02
0

When you initlialize a list using

seleksi = []

It is an empty list. The lenght of list is 0. Hence

seleksi[0] 

gives an error.

You need to append to the list for it to get values, something like

seleksi.append(p.select())

If you still want to assign it based on index, initialize it as array of zeros or some dummy value

seleksi = [0]* n

See this: List of zeros in python

Yuvraj Jaiswal
  • 1,605
  • 13
  • 20