What is the best way to join tuples?

Raymond Hettinger vze4rx4y at verizon.net
Fri Nov 15 14:47:20 EST 2002


"Terry Hancock" <hancock at anansispaceworks.com> wrote in message
> Hearsay says that list comprehensions are slower than regular loops, but
I've
> never actually compared them.  I doubt the difference is really
noticeable.
> Raymond's solution appears to be more general.

>
> Personally, I'm more interested in which is clearer.  I always find that I
> can't write a list comprehension (beyond really trivial cases) until I've
> written the solution out as a loop. But after the fact, when I look at the
> two, the list comprehension seems clearer (even in this case).

To help with the clarity comparison, here's are non-generalized versions:

# O(n) dictionary approach
xymatches = {}
for x,y,z in xyzTuple:
    xymatches.setdefault((x,y), []).append(z)
print [(w,x,y,z) for w,x,y in wxyTuple for z in xymatches.get((x,y), [-1])]

# O(n**2) double loop approach
wxyzTuple = [(w,x,y,z) for (w,x,y) in wxyTuple for (xp,yp,z) in xyzTuple if
(x,y)==(xp,yp)]
print wxyzTuple + [(w,x,y,-1) for (w,x,y) in wxyTuple if (x,y) not in [(x,y)
for (x,y,z) in xyzTuple]]

# O(n log n) sort/merge approach
I wasn't able to come-up with code that wasn't convoluted.





More information about the Python-list mailing list