对象操作:如何按月份分组并按数组位置对对应数值求和?
Solution to Group and Sum Monthly Data
Here's a straightforward way to achieve your desired result using Python. We'll use a dictionary to accumulate sums for each month, then convert it back to your target format.
Step-by-Step Code Implementation
from collections import defaultdict original = {"data":[["Dic",0,0,165,0],["Ene",0,0,200,0],["Ene",150,0,0,0],["Ene",150,20,10,500]]} # Initialize an accumulator to hold sums for each month monthly_sums = defaultdict(lambda: [0] * 4) # 4 numeric positions after the month name # Iterate through each entry and accumulate sums for entry in original["data"]: month = entry[0] values = entry[1:] for idx, val in enumerate(values): monthly_sums[month][idx] += val # Convert the accumulator to the desired format result = {"data": [[month] + sums for month, sums in monthly_sums.items()]} print(result)
Explanation
- Accumulator Setup: We use
defaultdictfrom thecollectionsmodule to automatically initialize a list of zeros for any new month we encounter. This saves us from manually checking if a month exists in the dict before adding values. - Summing Values: For each entry in the original data, we extract the month name and the numeric values. We then loop through each numeric value and add it to the corresponding position in the accumulator for that month.
- Formatting the Result: Finally, we convert the accumulator dictionary back into a list of lists, where each sublist starts with the month name followed by the summed values.
Output
Running this code will produce exactly your desired result:
{"data":[["Dic",0,0,165,0],["Ene",300,20,210,500]]}
Note: If you're using a Python version before 3.7, dictionaries don't preserve insertion order. To maintain the order of first occurrence of each month, you can use OrderedDict instead of defaultdict, or track the order separately.
内容的提问来源于stack exchange,提问作者Ricardo Antonio Hernández
相关产品推荐
相关产品推荐

