efficient intersection of lists with rounding
Raymond Hettinger
vze4rx4y at verizon.net
Fri Dec 3 03:55:27 EST 2004
"Gordon Williams" <g_will at cyberus.ca> wrote in message
news:mailman.7038.1102023963.5135.python-list at python.org...
> Hi,
>
> I have to lists that I need to find the common numbers (2nd rounded to
> nearest integral) and I am wondering if there is a more efficient way of
> doing it.
>
> >>> a= [(123,1.3),(123,2.4),(123,7.8),(123,10.2)]
> >>> b= [(123, 0.9), (123, 1.9), (123, 8.0)]
> >>> [ (i,round(j)) for i,j in a for l,m in b if (i,round(j)) ==
> (l,round(m))]
> [(123, 1.0), (123, 2.0), (123, 8.0)]
> >>>
> This works but a and b can be in the order of 30K long.
>
> A couple of other bits of info.
> - a and b are ordered smallest to largest (could bisect module be used?)
> - in the future I will want to round the second number of closest 0.25
> rather than whole number.
>
> Would the sets module be more efficient?
Yes:
>>> set((x,round(y)) for x,y in a) & set((x,round(y)) for x,y in b)
set([(123, 8.0), (123, 2.0), (123, 1.0)])
> I'm using python 2.3.
>>> from sets import Set as set
>>> set([(x,round(y)) for x,y in a]) & set([(x,round(y)) for x,y in b])
set([(123, 8.0), (123, 2.0), (123, 1.0)])
Raymond Hettinger
More information about the Python-list
mailing list