best way to determine sequence ordering?

Steven Bethard steven.bethard at gmail.com
Fri Apr 28 17:03:46 EDT 2006


John Salerno wrote:
> If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], 
> and then figure out if a certain element precedes another element, what 
> would be the best way to do that?
> 
> Looking at the built-in list functions, I thought I could do something 
> like:
> 
> if L.index('A') < L.index('D'):
>     # do some stuff

This is probably a pretty reasonable approach as long as you're not too 
worried about efficiency.  It scans the list twice though, so if you 
start doing this with really big lists, it might be better to do 
something like:

 >>> L = ['C', 'A', 'D', 'B']
 >>> positions = dict((item, i) for i, item in enumerate(L))
 >>> positions
{'A': 1, 'C': 0, 'B': 3, 'D': 2}
 >>> positions['A'] < positions['D']
True

If you care about memory in addition to speed, you could do something like:

 >>> L = ['C', 'A', 'D', 'B']
 >>> items_to_compare = ['A', 'D']
 >>> positions = dict(
...     (item, i)
...     for i, item in enumerate(L)
...     if item in items_to_compare
... )
 >>> positions
{'A': 1, 'D': 2}
 >>> positions['A'] < positions['D']
True

STeVe



More information about the Python-list mailing list