[英]How to merge duplicates in two lists of strings?
我对python(2.7)有点陌生,我很难做到这一点。
我有以下列表:
animal = ['cat', 'cat', 'dog', 'dog', 'dog', 'horse']
names = ['cat_01', 'cat_02', 'dog_01', 'dog_02', 'dog_03', 'horse_01']
我想要以下内容(可能是元组列表或字典)
new = {"cat":('cat_01','cat_02'), "dog":('dog_01','dog_02', 'dog_03'), "horse":('horse_01')}
如何做到最好?
使用列表理解的简短解决方案:
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
输出:
{'cat': ('cat_01', 'cat_02'), 'horse': ('horse_01',), 'dog': ('dog_01', 'dog_02', 'dog_03')}
您也可以从itertools
使用groupby
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)
当您的列表增加时,这可能会更快一些。
假设您的列表按示例中的顺序排序:
码:
my_dict = {}
for animal, name in zip(animals, names):
my_dict.setdefault(animal, []).append(name)
print(my_dict)
给出:
{'horse': ['horse_01'], 'dog': ['dog_01', 'dog_02', 'dog_03'], 'cat': ['cat_01', 'cat_02']}
如果您需要元组,则不列出:
my_dict = {k: tuple(v) for k, v in my_dict.items()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.