efficient intersection of lists with rounding

Steven Bethard steven.bethard at gmail.com
Thu Dec 2 19:37:52 EST 2004


Gordon Williams wrote:
> 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)]
>
[snip]
> Would the sets module be more efficient?

Well, in Python 2.3, I believe sets are implemented in Python while 
they're implemented in C in Python 2.4.  So probably not, unless you 
upgrade.  A 2.4 solution with sets:

 >>> a = [(123,1.3),(123,2.4),(123,7.8),(123,10.2)]
 >>> b = [(123, 0.9), (123, 1.9), (123, 8.0)]
 >>> def roundedj(pairs_iterable):
... 	return ((i, round(j)) for i, j in pairs_iterable)
...
 >>> set(roundedj(a)).intersection(set(roundedj(b)))
set([(123, 8.0), (123, 2.0), (123, 1.0)])

Steve



More information about the Python-list mailing list