2

我有一个重复的一些元素的列表。我需要根据另一个重复的元素组合一些元素。

示例输入:

[
('Sig: 7126', '10.3.5.0', 4),
('Sig: 7126', '10.3.5.0', 1),
('Sig: 7126', '10.3.5.0', 1),
('Sig: 3326', '10.3.5.0', 7),
('Sig: 7126', '10.3.5.1', 3),
('Sig: 7126', '10.3.5.1', 1),
('Sig: 7126', '10.3.5.2', 5),
('Sig: 7126', '10.3.5.2', 1),
('Sig: 7126', '10.3.5.4', 2),
('Sig: 7126', '10.3.5.4', 1),
('Sig: 7126', '10.3.5.4', 1),
('Sig: 7126', '10.3.5.4', 1),
('Sig: 0559', '10.3.5.34', 1),
('Sig: 7126', '10.3.5.34', 1),
('Sig: 7126', '10.3.5.34', 1),
('Sig: 0559', '10.3.5.42', 1),
('Sig: 7126', '10.3.5.42', 1),
('Sig: 7126', '10.3.5.43', 2)
]

目标是这样的:

[
('Sig: 7126', '10.3.5.0', 6),
('Sig: 3326', '10.3.5.0', 7),
('Sig: 7126', '10.3.5.1', 4),
('Sig: 7126', '10.3.5.2', 6),
('Sig: 7126', '10.3.5.4', 5),
('Sig: 0559', '10.3.5.34', 1),
('Sig: 7126', '10.3.5.34', 2),
('Sig: 0559', '10.3.5.42', 1),
('Sig: 7126', '10.3.5.42', 1),
('Sig: 7126', '10.3.5.43', 2)
]

有没有简单的python代码来实现它?

4

2 回答 2

1

itertools.groupby

 from itertools import groupby

l = [('Sig: 7126', '10.3.5.0', '4'), ('Sig: 7126', '10.3.5.0', '1')...]

def tuples_sum(iterable):
  return list(iterable[0][:-1]) + [sum(int(i[-1]) for i in iterable)]

for i, j in groupby(l, lambda x: (x[0], x[1])):
  print(tuples_sum(list(j)))

这使:

['Sig: 7126', '10.3.5.0', 6]
['Sig: 3326', '10.3.5.0', 7]
['Sig: 7126', '10.3.5.1', 4]
['Sig: 7126', '10.3.5.2', 6]
['Sig: 7126', '10.3.5.4', 5]
['Sig: 0559', '10.3.5.34', 1]
['Sig: 7126', '10.3.5.34', 2]
['Sig: 0559', '10.3.5.42', 1]
['Sig: 7126', '10.3.5.42', 1]
['Sig: 7126', '10.3.5.43', 2]
于 2013-04-21T18:41:22.907 回答
1

假设您按前两列分组:

import itertools

grouping = itertools.groupby(data, key=lambda i: (i[0], i[1]))
summer = lambda group: sum(i[2] for i in group))
result = [(a, b, summer(group)) for (a, b), group in grouping]

如果您的输入没有按分组键排序,则需要先对其进行排序:

import itertools

grouper = lambda item: (item[0], item[1])
data.sort(key=grouper)
grouping = itertools.groupby(data, key=grouper)

summer = lambda group: sum(i[2] for i in group)

result = [(a, b, summer(group)) for (a, b), group in grouping]
于 2013-04-21T18:45:50.907 回答