Uck
Uck

Reputation: 3

Have one list combine elements from another list based on index values

My goal is to have one list's duplicate items combine another list's elements together based on their corresponding index values, and also delete the first list's duplicates, so that there is still an equal number of indices for both lists.

Here's the start of the lists i'd like to change:

X = ['0', '1', '0', '1', '0', '1', '0']
Y = ['a', 'm', 'z', 'G', 'h', 'w', '22']

this is the result I'm looking for:

X = [0,1]
Y = ['azh22', 'mGw']

order also does not matter of the combined items in the second list (list Y) just as long as they're grouped together based on the items in list X.

I'm still a noobie with programming, and this one has me stumped. Thanks!

Upvotes: 0

Views: 150

Answers (2)

Blender
Blender

Reputation: 298392

Zip the two lists together:

In [15]: zip(X, Y)
Out[15]:
[('0', 'a'),
 ('1', 'm'),
 ('0', 'z'),
 ('1', 'G'),
 ('0', 'h'),
 ('1', 'w'),
 ('0', '22')]

And turn it into a dictionary:

from collections import defaultdict

d = defaultdict(str)

for key, value in zip(X, Y):
    d[key] += value  # If the key doesn't exist, it'll default to an empty string

And now you have your resulting dictionary, which I think will be easier to work with than two lists:

{'1': 'mGw', '0': 'azh22'}

Upvotes: 1

TerryA
TerryA

Reputation: 60004

You can use a defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(str)
>>> for i, j in zip(X, Y):
...     d[i] += j
... 
>>> print d
defaultdict(<type 'str'>, {'1': 'mGw', '0': 'azh22'})
>>> print d.items()
[('1', 'mGw'), ('0', 'azh22')]
>>> X = d.keys()
>>> Y = d.values()
>>> print X
['1', '0']
>>> print Y
['mGw', 'azh22']

Upvotes: 5

Related Questions