在列表中搜索并替换完全匹配的单词

时间:2019-04-23 23:55:09

标签: python python-3.x

我需要执行以下操作(下面的虚拟数据):

lookup = ['Chicken','Burger','Ham','Salmon','Chicken Breast']
example = [['Burger','1'], ['Ham','3'], ['Salmon','0'], ['Chicken','5'], ['Chicken Breast','2']]

在“示例”列表中,我需要用出现在“查找”列表中的相应索引替换食物名称。

因此输出应为: example = [['1', '1'], ['2', '3'], ['3', '0'], ['0', '5'], ['4', '2']]

我尝试了以下代码:

ctr=0
for y in lookup:
    example = [[x.replace(y,str(ctr)) for x in l] for l in example]
    ctr=ctr+1
print (example)

但是输出变为: [['1', '1'], ['2', '3'], ['3', '0'], ['0', '5'], ['0 Breast', '2']]

似乎我没有对“鸡”进行精确的单词匹配,它也将其替换为“鸡胸”。

我也尝试过

import re
ctr=0
for x in lookup:
    example = [[re.sub(r'\b'+x+r'\b', str(ctr), y) for y in l] for l in example]
    ctr=ctr+1

我仍然得到相同的结果。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

让我们尝试一些不同的东西。您可以将lookup转换成字典索引名称以进行索引。

然后您可以遍历example并通过在索引中查找名称来就地修改每个子列表的第一个元素。

m = {y: x for x, y in enumerate(lookup)}
for e in example:
    e[0] = m.get(e[0], e[0])

example
# [[1, '1'], [2, '3'], [3, '0'], [0, '5'], [4, '2']]

您还可以使用列表推导来重建example

example = [[m.get(x, x), y] for x, y in example]

答案 1 :(得分:1)

无需在查找中进行附加循环
试试这个:

example = [[lookup.index(l[0]),l[1]] for l in example]
print(example)
相关问题