擅长:python、mysql、java
<p>假设要对元组的第0个元素求和,如果不想使用dict,也可以使用<a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow noreferrer">^{<cd2>}</a>实现这一点,如下所示:</p>
<pre><code>from itertools import groupby
from operator import itemgetter
input = [
(1, 'project1', 'errorMessage1'),
(2, 'project1', 'errorMessage1'),
(3, 'project2', 'errorMessage1'),
(1, 'project3', 'errorMessage2'),
]
def sum_by_project_and_error(input):
# groupby needs the iterable to be sorted by the elements we want to group by.
# We sort by project and error message (the 1st and 2nd element of the tuples) using itemgetter.
key_function = itemgetter(1, 2)
sorted_input = sorted(input, key=key_function)
grouped_input = groupby(sorted_input, key=key_function)
for (project, error), group in grouped_input:
yield sum(count for count, _, _ in group), project, error
output = list(sum_by_project_and_error(input))
</code></pre>