I have 3 lists, a, b and c
Each of this lists contains tuples with 3 numbers.
Here is an example input:
a = [(1,2,4),(1,7,8),(1,5,4),(3,6,7)]
b = [(1,2,5),(1,9,3),(1,0,3),(3,6,8)]
c = [(2,6,3),(2,4,9),(2,8,5),(1,2,7)]
I'm looking for a way to generate a list that takes elements of those 3 lists if the two firsts items of eachs tuple are equals, and addind the third element.
In the data I gave, there is only 1 set of tuple with the 2 first values equals : (1,2,4), (1,2,5) and (1,2,7).
If I add their third value I have 4+5+7 = 16, so with those data, I should have [(1,2,16)] in the end.
The two first values are uniques in each list, [(1,2,7),(1,2,15)] won't exist.
The problem isn't finding tuples where only the two first values are equals, it's easyly done with a list comprehension. But I'm stuck on finding a pythonistic way to add the third value at the same time.
I can make this:
elem_list = []
for elem in a:
b_elem = [i for i in b if i[:-1] == elem[:-1]]
c_elem = [i for i in c if i[:-1] == elem[:-1]]
if len(b_elem) != 0 and len(c_elem) != 0:
elem_list.append((elem[0],elem[1], elem[2]+b_elem[0][2]+c_elem[0][2]))
That give me the desired output, but it's really long, and that's why I'm sure the is a pythonistic way to do this without trouble, I just can't figure it out.
解决方案
Here's one way to do it:
from itertools import product, starmap
def solve(*tups):
key = tups[0][:2]
if all(x[:2] == key for x in tups):
return key + (sum(x[2] for x in tups), )
for p in product(a, b, c):
out = solve(*p)
if out:
print out
#(1, 2, 16)
Or a one-liner using the above function:
print filter(None, starmap(solve, product(a, b, c)))
#[(1, 2, 16)]