简体   繁体   中英

How to merge duplicates in two lists of strings?

I am bit new with python (2.7) and I am having a hard time doing this.

I have the following lists:

animal = ['cat', 'cat', 'dog', 'dog', 'dog', 'horse']
names = ['cat_01', 'cat_02', 'dog_01', 'dog_02', 'dog_03', 'horse_01']

And I would like to have the following (it could be a list of tuples or a dict)

new = {"cat":('cat_01','cat_02'), "dog":('dog_01','dog_02', 'dog_03'), "horse":('horse_01')}

How best to do this?

Short solution using list comprehension:

animal = ['cat', 'cat', 'dog', 'dog', 'dog', 'horse']
names = ['cat_01', 'cat_02', 'dog_01', 'dog_02', 'dog_03', 'horse_01']
result = {a:tuple([n for n in names if a in n]) for a in animal}

print result

The output:

{'cat': ('cat_01', 'cat_02'), 'horse': ('horse_01',), 'dog': ('dog_01', 'dog_02', 'dog_03')}

You can also use groupby from itertools

from itertools import groupby
my_dict = {}
for key, groups in groupby(zip(animal, names), lambda x: x[0]):
    my_dict[key] = tuple(g[1] for g in groups)

This might be a little faster when your list grows.

Assuming your lists are sorted as they are in the example:

Code:

my_dict = {}
for animal, name in zip(animals, names):
    my_dict.setdefault(animal, []).append(name)
print(my_dict)

Gives:

{'horse': ['horse_01'], 'dog': ['dog_01', 'dog_02', 'dog_03'], 'cat': ['cat_01', 'cat_02']}

And if you need tuples not lists:

my_dict = {k: tuple(v) for k, v in my_dict.items()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM