繁体   English   中英

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

[英]search and replace exact word match in list of lists

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

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

我仍然得到相同的结果。

任何帮助表示赞赏。

让我们尝试一些不同的东西。 您可以将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]

无需额外的循环查找
尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM