[Tutor] single key ordered sequence

Jervis Whitley jervisau at gmail.com
Thu Jan 15 21:44:52 CET 2009


On Fri, Jan 16, 2009 at 4:56 AM, Senthil Kumaran <orsenthil at gmail.com>wrote:

> > Also, how to practically walk in reverse order in a list without
> > copying it (e.g. items[::-1]),
> > especially if i need both indexes and items (couldn't find with
> > enumerate()).
> >
> Are you looking for reversed()?
> The way you are doing it is probably OK.
> But it can be simplified thus:
>
> keys = []
> target = []
>
> for item in reversed(items):
>         if not item[0] in keys:
>                keys.append(item[0])
>                target.append(item)
>
> print target
>
> If this is not what you wanted,then I have misunderstood your
> requirement and just based it on your code.
>
> Thanks,
> Senthil
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

how about this:
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
            (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
mydict = dict(items)
items = [item for item in mydict.iteritems()]

testing shows:
C:\WINDOWS\system32\cmd.exe /c python test_time.py
**ORIGINAL**
s = """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
        (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for index in range(len(items)-1,-1,-1):
       key = items[index][0]
       if key in keys:
               items[index] = None
       else:
               keys.append(key)
items = [item for item in items if item is not None]
"""
timeit.Timer(stmt=s).timit()
5.40928835422

**Test1**
s = """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
            (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for item in reversed(items):
    key = item[0]
    if key in keys:
        items.remove(item)
    else:
        keys.append(key)
#items = [item for item in items if item is not None]
"""
timeit.Timer(stmt=s).timit()
5.02896436267

**Test2**
s= """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
            (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = dict(items)
items = [item for item in keys.iteritems()]
"""

timeit.Timer(stmt=s).timit()
3.38715506199
Hit any key to close this window...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090116/9b6563ef/attachment-0001.htm>


More information about the Tutor mailing list