What is the best way to join tuples?

Terry Reedy tjreedy at udel.edu
Thu Nov 14 01:38:24 EST 2002


"dique" <chezdique at yahoo.com> wrote in message
news:3dd32603$1_2 at news.tm.net.my...
> # I have two list of tuples, eg something like
> wxyTuple = [(1,1,1), (1,1,2), (1,2,1), (2,2,1)] # tuples of  (w,x,y)
> xyzTuple = [(1,1,0), (1,2,1), (1,1,2)] # tuples of (x,y,z)
>
> # and I want to join them together become (w,x,y,z), just like what
we used
> to do with RDBMS by joining two tables together, with x,y acting as
pivot.
> The result should be:
>
> wxyzTuple = [(1,1,1,0),(1,1,1,2),(1,1,2,1),(1,2,1,-1),(2,2,1,-1)] #
where -1
> is to indicate no match is found in xyzTuple

There are two approaches I would think about.

1. Sort both lists by (x,y) key and merge.

2. Put wxy items in dict mapping xy to w.  Then add xyz items, pairing
wz when both present.  Then extract key,value pairs and rewrite as
wanted.

Terry J. Reedy





More information about the Python-list mailing list