Home > Net >  Replace items of a longer list with matches from a shoter list
Replace items of a longer list with matches from a shoter list

Time:04-08

My goal is to compare two lists as follows:

Take every item in long_list and compare it for substrings to the entire short_list. If there is a match, add the item from the short_list to new_list. If no match, then insert 'NA' to new_list.

The issue with my current solution is, that the items from the long_list are inserted into new_list instead of the items from the short_list. How can I access b.

long_list = ['ABC', 'ABC', 'EFG', 'HIJ', 'XYZ', 'ABC', 'XYZ', 'KLM']
short_list = ['aABCa', 'xYZz']

new_list = [x if any(x.lower() in b.lower() for b in short_list) else 'NA' for x in long_list]. 

Current output:

new_list = ['ABC', 'ABC', 'NA', 'NA', 'XYZ', 'ABC', 'XYZ', 'NA']

Goal:

new_list = ['aABCa', 'aABCa', 'NA', 'NA', 'xXYZz', 'aABCa', 'xXYZz', 'NA']

CodePudding user response:

If you absolutly want to do it with a comprehension list you can use the folowing

>>> new_list = [next((y for y in short_list if x.lower() in y.lower()),'NA') for x in long_list]
>>> new_list
['aABCa', 'aABCa', 'NA', 'NA', 'xYZz', 'aABCa', 'xYZz', 'NA']

But a for loop might be clearer in this case

  • Related