2つの tuple の結合(1)に続けて、、、
結合元のタプルの要素数=2であるなら、
内包表示で、タプルのインデックスに注意を払えば、もっと簡単に書けるはずで、、
a = [ ('A',1103),('B',1104),('C',1105) ] b = [ ('A','red'),('C','yellow'),('D','blue') ]
dict() で、辞書を用意
a_dict = dict(a) b_dict = dict(b)
a LEFT JOIN b ON a[0] = b[0]
# a ← b a_left_b = [ (x[0], x[1], b_dict.get(x[0], None)) for x in a ]
b LEFT JOIN a ON b[0] = a[0]
# b ← a b_left_a = [ (x[0], a_dict.get(x[0], None), x[1]) for x in b ]
a LEFT JOIN b ON a[0] = b[0] WHERE b[2] NOT NULL
# a ← b where color is not null a_left_b_C = list(filter(lambda y:y[2] is not None, [ (x[0], x[1], b_dict.get(x[0], None)) for x in a ]))
b LEFT JOIN a ON b[0] = a[0] WHERE a[2] NOT NULL
# b ← a where color is not null b_left_a_C = list(filter(lambda y:y[1] is not None, [ (x[0], a_dict.get(x[0], None), x[1]) for x in b ]))
print(a_dict) print(b_dict) print('\n-- a LEFT JOIN b ON a.name=b.name --') print(a_left_b) print('\n-- b LEFT JOIN a ON b.name=a.name --') print(b_left_a) print('\n-- a LEFT JOIN b ON a.name=b.name WHERE color is not null --') print(a_left_b_C) print('\n-- b LEFT JOIN a ON b.name=a.name WHERE id not null --') print(b_left_a_C)
print の結果
{'A': 1103, 'B': 1104, 'C': 1105} {'A': 'red', 'C': 'yellow', 'D': 'blue'} -- a LEFT JOIN b ON a.name=b.name -- [('A', 1103, 'red'), ('B', 1104, None), ('C', 1105, 'yellow')] -- b LEFT JOIN a ON b.name=a.name -- [('A', 1103, 'red'), ('C', 1105, 'yellow'), ('D', None, 'blue')] -- a LEFT JOIN b ON a.name=b.name WHERE color is not null -- [('A', 1103, 'red'), ('C', 1105, 'yellow')] -- b LEFT JOIN a ON b.name=a.name WHERE id not null -- [('A', 1103, 'red'), ('C', 1105, 'yellow')]