同时交叉和添加列表元素的Python方式 [英] Pythonistic way to intersect and add elements of lists at the same time

查看:132
本文介绍了同时交叉和添加列表元素的Python方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个列表,abc

每个列表包含具有3个数字的元组.

Each of this lists contains tuples with 3 numbers.

以下是示例输入:

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

我正在寻找一种生成列表的方法,如果每个元组的两个第一项相等,则采用这3个列表的元素,然后添加第三个元素.

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.

在我提供的数据中,只有1组元组,两个第一个值分别等于:(1,2,4)(1,2,5)(1,2,7).

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

如果我将它们的第三个值相加,我将得到4+5+7 = 16,因此对于这些数据,我应该最后加上[(1,2,16)].

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.

每个列表中的前两个值都是唯一的,[(1,2,7),(1,2,15)]将不存在.

The two first values are uniques in each list, [(1,2,7),(1,2,15)] won't exist.

问题不是找到只有两个第一个值相等的元组,而通过列表理解很容易做到.但是我一直坚持寻找一种pythonistic的方法来同时添加第三个值.

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.

我可以做到这一点:

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

这给了我想要的输出,但是它确实很长,这就是为什么我确定这是一种Python方式可以毫无困难地做到这一点,我只是想不通.

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.

推荐答案

这里是一种方法:

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

这篇关于同时交叉和添加列表元素的Python方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆