小编Cod*_*st 的帖子

将句子中的键替换为其值

我有一本字典和一个清单

dict1= {'good':'bad','happy':'sad','pro':'anti'}
Run Code Online (Sandbox Code Playgroud)
list1=['she is good','this is a product','they are pro choice']
Run Code Online (Sandbox Code Playgroud)
newlist=[]
for index, data in enumerate(list1):
    for key, value in dict1.items():
        if key in data:
            list1[index]=data.replace(key, dict1[key])
            newlist.append(list1[index])
Run Code Online (Sandbox Code Playgroud)
The output I get is
['she is bad','this is a antiduct','they are anti choice']

desired output is
['she is bad','this is a product','they are anti choice']
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?它也正在取代产品的专业版。我只希望它作为独立词存在时取代 pro。

python dictionary key list key-value

0
推荐指数
1
解决办法
46
查看次数

标签 统计

dictionary ×1

key ×1

key-value ×1

list ×1

python ×1