[英]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.