iheartcpp - 2 months ago 7x
Python Question

# Joining elements in list in python

I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.

``````a = ['x', 'y', 'z', 'z', 'x', 'w']
b = [  1,   4,   5,   7,   9,  5]
c = [  3,   6,   7,   8,   9,  7]
``````

After processing,

``````a = ['x', 'y',  'z',  'w']
b = [ 10,   4,   12,   5 ]
c = [ 12,   6,   15,   7 ]
``````

Could do something like this using OrderedDict, since you need to maintain the same order:

``````from collections import OrderedDict

a = ['x', 'y', 'z', 'z', 'x', 'w']
b = [  1,   4,   5,   7,   9,  5]
c = [  3,   6,   7,   8,   9,  7]
b_data = OrderedDict()
c_data = OrderedDict()

for letter, value in zip(a, b):
if letter in b_data:
b_data[letter] += value
else:
b_data[letter] = value

for letter, value in zip(a, c):
if letter in c_data:
c_data[letter] += value
else:
c_data[letter] = value

a = b_data.keys()
b = b_data.values()
c = c_data.values()

print(a)
print(b)
print(c)
``````

Output:

``````['x', 'y', 'z', 'w']
[10, 4, 12, 5]
[12, 6, 15, 7]
``````
Source (Stackoverflow)