Reputation: 9
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?
Upvotes: 0
Views: 138
Reputation: 42796
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)
Upvotes: 0
Reputation: 1217
[]
, 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()
Upvotes: 1
Reputation: 1723
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
Upvotes: 0