【发布时间】:2017-06-16 03:10:29
【问题描述】:
我有一个字符串列表、一个单词字典及其替换:
titles = ['The cat in the hat', 'Horton hears a who', \
'Green eggs and ham', 'The butter battle book', 'My book about me']
wlist = {'cat': 'word1', 'hat': 'word2', 'Horton': 'word3', \
'eggs': 'word4', 'butter': 'word5', 'book': 'word6'}
如果在字符串中找到,我需要用它们对应的值替换字典中作为键出现的单词。
到目前为止,我有以下代码:
for i, book in enumerate(titles):
for k,v in wlist.items():
if k in book:
book = book.replace(k, v)
titles[i] = book
这给了我输出:
['The word1 in the word2',
'word3 hears a who',
'Green word4 and ham',
'The word5 battle word6',
'My word6 about me']
有没有更有效(更快)的方法来做到这一点,也许没有两个 for 循环?我实际上拥有的清单很大!
非常感谢!
【问题讨论】:
标签: python-3.x