2017-02-19 150 views
0

我對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')} 

如何最好地做到這一點?

回答

0

假設你的列表進行排序,因爲它們是在例如:

代碼:

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()} 
1

簡短的解決方案使用列表理解:

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')} 
+0

這會改變'in'運算符的'str.startwith'。因爲我正在處理不以我需要的字符串開頭的文件路徑。不管怎樣,謝謝你! –

+0

如果是這樣,我已經改變了這個片段。它會工作 – RomanPerekhrest

1

您還可以使用groupbyitertools

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) 

這可能會快一點當你的名單增長。

相關問題