求和Python元组子集((1,john),(2,joey))=(3,john + joey)

时间:2015-04-28 01:22:29

标签: python tuples

我试图将子集中的所有元组一起添加。

到目前为止,我有:

list(itertools.combinations(((1, 'aa'), (2, 'bb'), (3, 'cc'), (4, 'dd'),
(5, 'ee'), (6, 'ff'), (7, 'gg'), (8, 'hh')), 6))

产生:

((1, 'aa'), (2, 'bb'), (5, 'ee'), (6, 'ff'), (7, 'gg'), (8, 'hh')), 
((1, 'aa'), (3, 'cc'), (4, 'dd'), (5, 'ee'), (6, 'ff'), (7, 'gg')),

但我想将所有数值加在一起,将非数值加在一起,如:

(29, 'aa'+'bb'+'ee'+'ff'+'gg'+'hh')

然后我想以最大值按升序对它们进行排序。我在mathematica中占据了一条线,让我在python中疯狂。

1 个答案:

答案 0 :(得分:4)

如果您对列表推导/生成器表达式感到满意,您肯定可以在Python中的一行(和一点点)中执行此操作:

combs = list(itertools.combinations(
    ((1, 'aa'), (2, 'bb'), (3, 'cc'), (4, 'dd'),
     (5, 'ee'), (6, 'ff'), (7, 'gg'), (8, 'hh')), 
    6
))
sums = [
    (sum(n for n, text in comb), ''.join(text for n, text in comb)) 
    for comb in combs
]

# Will sort by number first, then text, by default
sorted(sums)
Out[8]: 
[(21, 'aabbccddeeff'),
 (22, 'aabbccddeegg'),
 (23, 'aabbccddeehh'),
 (23, 'aabbccddffgg'),
 (24, 'aabbccddffhh'),
 (24, 'aabbcceeffgg'),
 (25, 'aabbccddgghh'),
 (25, 'aabbcceeffhh'),
 # Etc.