2

I have arrays like this:

['[camera_positive,3]', '[lens_positive,1]', '[camera_positive,2]', '[lens_positive,1]', '[lens_positive,1]', '[camera_positive,1]']

How to sum all value on index [1] with same string on index [0]?
Example:

camera_positive = 3 + 2 + 1 = 6
lens_positive = 1 + 1 + 1 = 3
3
  • do you know the strings in advance? Commented Jul 20, 2017 at 23:29
  • that is a list of strings, not a list of lists? Is that correct? Commented Jul 20, 2017 at 23:31
  • What have you tried? Are you familiar with list comprehensions? Have you used the Collections package at all? These are useful tools for the problem. Commented Jul 20, 2017 at 23:33

3 Answers 3

1

You could use set in order to extract the unique keys and then use list comprehension to compute the sum for each key:

data = [['camera_positive', 3], 
        ['lens_positive', 1], 
        ['camera_positive', 2], 
        ['lens_positive', 1], 
        ['lens_positive', 1], 
        ['camera_positive', 1]]

keys = set(key for key, value in data)

for key1 in keys:
    total = sum(value for key2, value in data if key1 == key2)
    print("key='{}', sum={}".format(key1, total))

this gives:

key='camera_positive', sum=6
key='lens_positive', sum=3
Sign up to request clarification or add additional context in comments.

1 Comment

sorry that was my mistake, i've delete my recent comment in this section. I've tried your suggestion and it works like a charm! So simple, no need library and etc. I've accepted your answer, thank you!
0

I'm assuming that you have a list of list, not a list of strings as shown in the question. Otherwise you'll have to do some parsing. That said, I would solve this problem by creating a dictionary, and then iterating over the values and adding them to the dictionary as you go.

The default dict allows this program to work without getting a key error, as it'll assume 0 if the key does not exist yet. You can read up on defaultdict here: https://docs.python.org/3.3/library/collections.html#collections.defaultdict

lmk if that helps!

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d
defaultdict(<class 'int'>, {})
>>> lst=[['a',1], ['b', 2], ['a',4]]
>>> for k, v in lst:
...   d[k] += v
... 
>>> d
defaultdict(<class 'int'>, {'a': 5, 'b': 2})

Comments

0

You could group the entries by their first index using groupby with lambda x: x[0] or operator.itemgetter(0) as key.

This is maybe a bit less code than what Nick Brady showed. However you would need to sort the list first (for the same key), so it might be slower than his approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.