What is the best way to join tuples?

dique chezdique at yahoo.com
Wed Nov 13 23:31:02 EST 2002


# 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

# I tried this:
wxyzFunc = lambda (w,x,y,z): (w,x,y) in wxyTuple and ((x,y,z) in xyzTuple or
z==-1)
wxyzTuple = filter(wxyzFunc, [(w,x,y,z[2]) for (w,x,y) in wxyTuple for z in
xyzTuple+[(0,0,-1)]])
print wxyzTuple

# but the result is [(1, 1, 1, 0), (1, 1, 1, 2), (1, 1, 1, -1), (1, 1, 2,
1), (1, 1, 2, -1), (1, 2, 1, -1), (2, 2, 1, -1)]
# which is not intended, as it also contains those noises like (1,1,1,-1)
# How should I go about it? Thanx!!





More information about the Python-list mailing list