简体   繁体   中英

search and replace exact word match in list of lists

I need to execute the following (dummy data below):

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

In 'example' list of lists, I need to replace the food name with respective index as it appears in the 'lookup' list.

So the output should be: example = [['1', '1'], ['2', '3'], ['3', '0'], ['0', '5'], ['4', '2']]

I tried the following code:

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)

But the output becomes: [['1', '1'], ['2', '3'], ['3', '0'], ['0', '5'], ['0 Breast', '2']]

It appears I'm not performing an exact word match for 'Chicken' that it also replaces it in 'Chicken Breast'

I also tried

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

I still get the same result.

Any help is appreciated.

Let's try something different. You can convert lookup into a dictionary mapping name to index.

You can then iterate over example and modify the first element of each sublist in-place by lookup up the name in the index.

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']]

You could also use a list comprehension to reconstruct example :

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

No need for additional loop on lookup
Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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