L.hue
L.hue

Reputation: 41

Python: how to detect duplicates in a list to signal a different operation

I have a large table of data that I have split into individual lists, for example:(lists virticle)

A=[1,1,2,2,3,3,3]
B=[6,3,5,3,8,4,3]

What I would like to achieve is 2 new lists where list A is condensed down into non-repeating values and where a repeated value occurs in A the new corrosponding value of B is the addition of its elements corresponding to that value, for example I would like the two new lists to be:

C=[1,2,3]
D=[9,8,15]

I would like to extend this over a much larger amount of data in the lists, how could I achieve this?

Upvotes: 4

Views: 174

Answers (3)

Lunkle
Lunkle

Reputation: 145

Heyo, perhaps this is a more simpler way of doing it. I just used some for loops and stuffs.

a = [1,1,2,2,3,3,3]
b = [6,3,5,3,8,4,3]
c = []
d = []
dValue = 0 #Used for keeping track of what goes in d array

for index in range(len(a)):
    try:
       c.index(a[index])    #See if program has already checked a duplicate value
    except:                 #If not checked, do the following; If has checked, do nothing
        c.append(a[index])   #Place value in c array
        for sameNumbers in range(len(a)):    #Here checking for duplicate values
            if a[sameNumbers] == a[index]:
                dValue += b[sameNumbers]    #dValue increases by the corresponding b index
        d.append(dValue)     #Put dValue in array
        dValue = 0           #Reset dValue for next time

print(c, d) #[1, 2, 3],[9, 8, 15]

Upvotes: 0

SparkAndShine
SparkAndShine

Reputation: 18017

Use itertools.groupby,

import itertools
import operator
import collections

A=[1,1,2,2,3,3,3] 
B=[6,3,5,3,8,4,3]

d = collections.OrderedDict()

for key, group in itertools.groupby(zip(A, B), key=operator.itemgetter(0)):
    d[key] = sum(map(operator.itemgetter(1), group))


C = d.keys()        # [1, 2, 3]
D = d.values()      # [9, 8, 15]

In one line using list comprehensions,

d = collections.OrderedDict({key : sum(map(operator.itemgetter(1), group)) 
                            for key, group in itertools.groupby(zip(A, B), key=operator.itemgetter(0))})

Upvotes: 2

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

Use a dictionary to add the values. Then make 2 lists from that dictionary. One from the keys and another from the values.

A = [1,1,2,2,3,3,3] 
B = [6,3,5,3,8,4,3]

Concate = dict()

for i in range(len(A)):

    if(A[i] in Concate):
        Concate[A[i]]+=B[i]
    else:
        Concate.update({A[i]:B[i]})

C = list(Concate.keys())
D = list(Concate.values())
print("C=",C)
print("D=",D)

Upvotes: 1

Related Questions