Python problem

W

WIWA

Hi all,



I'm trying to write the following in python:



j=0

for i in range(len(datumlijst)+1):

if (datumlijst[i+1]!=datumlijst):

datum[j]=datumlijst

j=j+1



print datum[:]



it complains about the part: datumlijst[i+1]!=datumlijst



it produces the following error:



File "hits_per_dag.py", line 24, in ?

datum[j]=datumlijst

IndexError: list assignment index out of range



Anyone know why this happens
 
P

Peter Otten

WIWA said:
I'm trying to write the following in python:
j=0

for i in range(len(datumlijst)+1):
if (datumlijst[i+1]!=datumlijst):
datum[j]=datumlijst
j=j+1
print datum[:]

it complains about the part: datumlijst[i+1]!=datumlijst
You are comparing a list with a list entry which is probably unintended.
datum[j]=datumlijst

IndexError: list assignment index out of range
You seem to assume that a list grows automatically. That's not true in
Python.

Now here's my guess of your intentions:

datumlijst = [1,1,2,2,3,4,5,5,5,5,6,3]
datumlijst.sort()
datum = [datumlijst[0]]

for i in range(len(datumlijst)-1): # all list indexes start with 0
if datumlijst[i+1] != datumlijst: # both indexed
datum.append(datumlijst[i+1]) # note the append()

print datum #no need for [:]

There may still sit a bug in the above. The following should be a little
more robust, e. g. no need to sort datumlijst, no extensive use of list
indexes:

from sets import Set
datumlijst = [1,1,2,2,3,4,5,5,5,5,6,3]
print list(Set(datumlijst))

This is Python 2.3 only, in 2.2 you can do it with a dictionary, using the
keys only.

Peter

PS: I see you've already fallen in love with whitespace :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top