[[+content_image]]
V
V
VaniLuksh2020-02-17 13:31:43
Python
VaniLuksh, 2020-02-17 13:31:43

How to add list items over other list items?

There is a list of lists: You need to add the first numbers of the lists by the values ​​of the second elements, i.e. group by the second elements of the list
num_list = [[5, 1], [10, 1], [30, 2], [20, 2]]

sum_list1 = [15, 1]
sum_list2 = [50, 2]

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
dob, 2020-02-17
@VaniLuksh

for e in set([l[-1] for l in num_list]):
    print([e, sum([l[0] for l in num_list if l[1] == e])])

Or get a generator:
def get_iter(num_list):
    for e in set([l[-1] for l in num_list]):
        yield [sum([l[0] for l in num_list if l[1] == e]), e]

for e in get_iter(num_list):
    print(e)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question