comparing two lists and returning "position"

Paul Rubin http
Mon Jun 25 16:17:30 CEST 2007


Charles Sanders <C.delete_this.Sanders at BoM.GOv.AU> writes:
> from itertools import izip, count
> d = dict(izip(l2,count()))
> pos = [ d[i] for i in l1 ]
> 
> or the more memory intensive
> 
> d = dict(zip(l2,range(len(l2))))
> pos = [ d[i] for i in l1 ]

If you're itertools-phobic you could alternatively write

  d = dict((x,i) for i,x in enumerate(l2))
  pos = [ d[i] for i in l1 ]

dict access and update is supposed to take approximately constant time,
btw.  They are implemented as hash tables.



More information about the Python-list mailing list