Find duplicates in list

I have a list containing values ​​like below

h = [
    ('red', array([50, 344])),
    ('blue', array([15, 55])),
    ('green', array([1, 1])),
    ('orange', array([3, 7])),
    ('red', array([1, 1]))
]

I want to scroll through the list and summarize numpy.arrays if the labels are the same. Therefore, given the example above, since there are two “red” instances, the desired result will be the same list, but

('red', array([ 50, 344])) + ('red', array([1, 1])) = ('red', array([51, 345]))

I tried to have a nested loop like

for i in range(0, len(h)):
    for p in range(0, len(h)):
        if (h[i][0] == h[p][0]):
            A = h[i][1] + h[p][1]

However, this code also summarizes the value of the instance h[i][0]with itself, but I don't want that. I want to do the following - for each instance, if the label of the other instances without me is the same, add them to me without adding my value to yourself. Hope clear

+4
source share
2 answers

I would recommend using a dictionary for this:

out = {}
for colour, array_ in h:
     if colour in out:
         out[colour] += array_
     else:
         out[colour] = array_

out.items(), .

[('blue', array([15, 55])), ('orange', array([3, 7])), 
 ('green', array([1, 1])), ('red', array([ 51, 345]))]

.

, , , .

+4

if i==p: 
  continue

, 0, , 0.

0

Source: https://habr.com/ru/post/1535708/


All Articles