如何通过它自己的索引或python中的某些值来减去元组的元素

时间:2017-06-14 16:48:59

标签: python tuples elements subtraction

R = [(1, 2,3,4), (1, 3), (1, 4), (1,4, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

从上面的集合中我只想减去索引或元组中每个元素的任何值。

预期的答案是

#R = [(1-0, 2-0,3-0,4-0), (1-1, 3-1), (1-2, 4-2) and so on

这是我的代码,但我想用最简单的方式来帮助

final_matches = {k: v for k,v in matches.items() if len(v) >= 4}

    for k, v in matches.items():
        if len(v) >= 3:
            print(k,':',v,'/',len(v))
            #for j in range(0,len(v)):
                #print(v[j])

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

R = [(1, 2,3,4), (1, 3), (1, 4), (1,4, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

new_list = [tuple(c-i for c in a) for i, a in enumerate(R)]

只获得长度为3的元组:

new_list = [i for i in new_list if len(i) >= 3]

最终输出:

[(1, 2, 3, 4), (-2, 1, 2)]

答案 1 :(得分:0)

当你遍历字典时,

v[:] = [x - k for x in v]可以做到这一点。