[[+content_image]]
S
S
Sod802021-09-17 17:40:30
Python
Sod80, 2021-09-17 17:40:30

Working with multidimensional lists?

Good afternoon. How to set a condition for a multidimensional list? For example, add all elements with index 1, provided that the zero elements are the same.
For example T =[[1,1],[1,2],[2,2],[2,4],[1,5],[1,6]]
Just started learning the language. I can not describe the condition of equality of zero elements.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
ScriptKiddo, 2021-09-17
@Sod80

from collections import defaultdict

t = [[1, 1], [1, 2], [2, 2], [2, 4], [1, 5], [1, 6]]

d = defaultdict(int)

for item in t:
    d[item[0]] += item[1]

print(d)

OUT
defaultdict(<class 'int'>, {1: 14, 2: 6})

Process finished with exit code 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question