Skip to content

Instantly share code, notes, and snippets.

@hygull
Last active November 23, 2019 05:30
Show Gist options
  • Save hygull/949d8551edb3323de1cb82e111dfdfdf to your computer and use it in GitHub Desktop.
Save hygull/949d8551edb3323de1cb82e111dfdfdf to your computer and use it in GitHub Desktop.
Regex list dict based Python question for beginners

https://stackoverflow.com/a/59004613/6615163

In [1]: import re                                                                        

In [2]: listA = ['123', '345', '678']                                                    

In [3]: listB = ['ABC123', 'CDE455', 'GHK678', 'CGH345']                                 

In [4]: # Mapping b/w number in listB to related index                                   

In [5]: mapping = {re.sub(r'\D+', '', value).strip(): index for index, value in enumerate(listB)}                                                                         

In [6]: mapping # Print mapping dictionary                                               
Out[6]: {'123': 0, '455': 1, '678': 2, '345': 3}

In [7]: # Find the desired output                                                        

In [8]: output = [mapping.get(item) for item in listA]                                   

In [9]: output                                                                           
Out[9]: [0, 3, 2]

In [10]:   
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment