Reputation: 11
Been trying to figure out a way to sum up each and every index in a list of lists in Python. For example a list of list like this:
carbon_dioxide = ([" ", "1990", "1991", "1992"], ["factories", "100", "101", "102"], ["food industry", "50", "51", "52"], ["transports", "25", "26", "27"])
I want to exclude the first list and then sum up index 1 in list 2 ("100") with index 1 in list 3 ("50") and 4 ("25").
Then i want the iteration to continue and sum up index 2 in all the lists.
I do not want to import any modules, just pure code since I am a beginner trying to grasp the basics. I tried different solutions but no. For example this one, but it gave me the whole list of lists except from list[0]:
for i in range(1, len(carbon_dioxide)):
print(carbon_dioxide[i])
Do you have any ideas? Thanks!
Upvotes: 1
Views: 173
Reputation: 14216
It sounds like you want to add carbon dioxide levels for each year if I am not mistaken. A more digest-able output might be a dictionary where you have a year to (sum of carbon dioxide levels) mapping.
year_nums = zip(*(c[1:] for c in carbon_dioxide)) # gives us a year and all the CO2 levels
output = {yn[0]: sum(map(int, yn[1:])) for yn in year_nums}
print(output)
>> {'1990': 175, '1991': 178, '1992': 181}
Upvotes: 1
Reputation: 17156
Adding to your start.
results = [0]*(len(carbon_dioxide[0])-1) # Initialize array for results
# with all zeros
for sublist in carbon_dioxide[1:]: # skips 1st sublist in crbon_dioxide
for index, v in enumerate(sublist[1:]): # skips first item in each sublist
# i.e. skips "", "factories", etc.
results[index] += int(v) # Add to result at index 'index'
print(results) # [175, 178, 181]
Upvotes: 0
Reputation: 6090
I am not sure that is what you're looking for, still:
carbon_dioxide = ([" ", "1990", "1991", "1992"], ["factories", "100", "101", "102"], ["food industry", "50", "51", "52"], ["transports", "25", "26", "27"])
for k in range(1,4):
for i in range(1, len(carbon_dioxide)):
for j in range(i+1,len(carbon_dioxide)):
carbon_dioxide[i][k] = int(carbon_dioxide[i][k]) + int(carbon_dioxide[j][k])
print(carbon_dioxide)
Output:
([' ', '1990', '1991', '1992'], ['factories', 175, '101', '102'], ['food industry', 75, '51', '52'], ['transports', '25', '26', '27'])
([' ', '1990', '1991', '1992'], ['factories', 175, 178, '102'], ['food industry', 75, 77, '52'], ['transports', '25', '26', '27'])
([' ', '1990', '1991', '1992'], ['factories', 175, 178, 181], ['food industry', 75, 77, 79], ['transports', '25', '26', '27'])
Upvotes: 0