python交叉输出_同时交叉和添加列表元素的Python方式

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)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值