Python problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • WIWA

    Python problem


    Hi all,



    I'm trying to write the following in python:



    j=0

    for i in range(len(datum lijst)+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.p y", line 24, in ?

    datum[j]=datumlijst

    IndexError: list assignment index out of range



    Anyone know why this happens


    --
    Posted via http://dbforums.com
  • Peter Otten

    #2
    Re: Python problem

    WIWA wrote:[color=blue]
    >
    > I'm trying to write the following in python:[/color]
    [color=blue]
    > j=0
    >
    > for i in range(len(datum lijst)+1):
    > if (datumlijst[i+1]!=datumlijst):
    > datum[j]=datumlijst
    > j=j+1[/color]
    [color=blue]
    > print datum[:]
    >
    > it complains about the part: datumlijst[i+1]!=datumlijst
    >[/color]
    You are comparing a list with a list entry which is probably unintended.
    [color=blue]
    > datum[j]=datumlijst
    >
    > IndexError: list assignment index out of range
    >[/color]
    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(datum lijst)-1): # all list indexes start with 0
    if datumlijst[i+1] != datumlijst[i]: # both indexed
    datum.append(da tumlijst[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(datuml ijst))

    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 :-)

    Comment

    Working...