[英]Python replace comma separated words in list to dictionary value if existed in dictionary key
I would like to replace words to corresponding dictionary key:value if exist.如果存在,我想将单词替换为相应的字典键:值。 For example, I have a comma separated list
例如,我有一个逗号分隔的列表
unfiltered = ['Cat,Dog,Cow','','Horse,Whale','Fish,Giant Elephant']
and would like to change 'Whale' to 'Big Whale' and 'Fish' to 'Jellyfish' like this dictionary:并想像这本词典一样将“鲸鱼”更改为“大鲸鱼”,将“鱼”更改为“水母”:
word_to_change = {'Whale': 'Big Whale', 'Fish': 'Jellyfish'}
to make the result like this:使结果像这样:
['Cat,Dog,Cow','','Horse,Big Whale','Jellyfish,Giant Elephant']
I could combine all the elements in 'unfiltered' list and filtered with dictionary value:我可以组合“未过滤”列表中的所有元素并使用字典值过滤:
unfiltered_combine = ['Cat','Dog','Cow','','Horse','Whale','Fish','Giant Elephant']
[x if x not in word_to_change else word_to_change[x] for x in lists]
Result when filtering combined words:过滤组合词时的结果:
['Cat', 'Dog', 'Cow', '', 'Horse', 'Big Whale', 'Jellyfish', 'Giant Elephant']
However, I want to keep the list 'unfiltered' without combining its elements.但是,我想在不组合其元素的情况下保持列表“未过滤”。 Is there any way to filter the 'unfiltered' list to 'word_to_change' dictionary key:value?
有什么方法可以将“未过滤”列表过滤为“word_to_change”字典键:值? I would sincerely appreciate if you could give some advice.
如果您能给我一些建议,我将不胜感激。
You can us the following comprehension:您可以通过我们以下的理解:
unfiltered = ['Cat,Dog,Cow', '', 'Horse,Whale', 'Fish,Giant Elephant']
wtc = {'Whale': 'Big Whale', 'Fish': 'Jellyfish'}
result = [','.join(wtc.get(s, s) for s in e.split(',')) for e in unfiltered]
# ['Cat,Dog,Cow', '', 'Horse,Big Whale', 'Jellyfish,Giant Elephant']
This makes use of the dict.get(key, default)
method.这使用了
dict.get(key, default)
方法。 Yousplit
the list elements, apply the conversion and join
the tokens back together.您
split
列表元素,应用转换,并join
令牌重新走到一起。
unfiltered = ['Cat,Dog,Cow','','Horse,Whale','Fish,Giant Elephant']
word_to_change = {'Whale': 'Big Whale', 'Fish': 'Jellyfish'}
for key, value in word_to_change.items():
unfiltered = [w.replace(key, value) for w in unfiltered]
Output:输出:
['Cat,Dog,Cow', '', 'Horse,Big Whale', 'Jellyfish,Giant Elephant']
Edited: only works properly if the new values are not in the initial list.编辑:仅当新值不在初始列表中时才能正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.