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?

1
  • What does this line do seleksi[0] = p.select() ? Commented May 11, 2018 at 11:44

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)

3 Comments

and i got this selections.writerow(selections) _csv.Error: sequence expected @Netwave
@RozBarb, i think you want to write x, so selections.writerow(x)
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.