Python嵌套列表按首元素聚合求和问题及代码调试求助
Let's break down how to solve this grouping and summing problem, and also figure out why your original approach with list.index() wasn't working.
Why list.index() Caused Issues
The list.index(item) method returns the first occurrence of the item in the list. So when you loop through your nested list and hit the second ['a', 3, 12], calling index() would point you back to the first ['a',14,2] entry. If your code was trying to modify the original list in-place, this would lead to either overwriting values incorrectly or failing to accumulate sums for subsequent entries with the same first element—hence why your output matched the original list.
Solution 1: Use a Dictionary for Aggregation
The most straightforward way to group by the first element and sum the values is to use a dictionary, where keys are the unique first elements, and values are lists holding the accumulated sums. Here's how to implement it:
original_list = [ ['a',14,2], ['b',10,1], ['a',3,12], ['r',5,5], ['r',6,13] ] aggregation_dict = {} for entry in original_list: key = entry[0] val1, val2 = entry[1], entry[2] if key in aggregation_dict: # Add to existing sums aggregation_dict[key][0] += val1 aggregation_dict[key][1] += val2 else: # Initialize new entry for the key aggregation_dict[key] = [val1, val2] # Convert the dictionary back to the desired nested list format result = [[key] + values for key, values in aggregation_dict.items()] print(result) # Output: [['a', 17, 14], ['b', 10, 1], ['r', 11, 18]]
Solution 2: Simplify with collections.defaultdict
If you want cleaner code, use defaultdict from the collections module to avoid checking if a key exists every time:
from collections import defaultdict original_list = [ ['a',14,2], ['b',10,1], ['a',3,12], ['r',5,5], ['r',6,13] ] aggregation_dict = defaultdict(lambda: [0, 0]) # Initialize sums to 0 for new keys for key, val1, val2 in original_list: aggregation_dict[key][0] += val1 aggregation_dict[key][1] += val2 result = [[key] + values for key, values in aggregation_dict.items()] print(result)
What About Using set?
You were right that set alone can't handle the summation—since sets only store unique values, they can't track the accumulated sums. However, you could use a set to get all unique first elements, then loop through the original list to calculate sums for each key. But this would require two passes over the list, which is less efficient than the dictionary approach above.
For example (not recommended over the dictionary methods, but just to show it's possible):
original_list = [ ['a',14,2], ['b',10,1], ['a',3,12], ['r',5,5], ['r',6,13] ] unique_keys = {entry[0] for entry in original_list} result = [] for key in unique_keys: sum1 = sum(entry[1] for entry in original_list if entry[0] == key) sum2 = sum(entry[2] for entry in original_list if entry[0] == key) result.append([key, sum1, sum2]) # Note: The order might vary since sets are unordered; if you need consistent order, use sorted(unique_keys) print(result)
内容的提问来源于stack exchange,提问作者Yafim Simanovsky

