Generate list from master list with matching words, irrespective of the sequence

Viewed 66

I have created a list, lets call it master list

master=['abc 1.2 px', 'pqr 5.4 tr', '1.8 cmq', 'pst 2.5']

Now I am having another list like

l1=['1.2 abc px', 'pqr tr 5.4', 'cmq 1.8', '1.8 cmq', '2.5 pst', 'abc 1.2 px']

I want to modify l1 which will take the names from master where all words are presents irrespective of sequence. for example the modified list will be

l2=['abc 1.2 px', 'pqr 5.4 tr', '1.8 cmq', '1.8 cmq', 'pst 2.5','abc 1.2 px']

How to do it using python ?

1 Answers

Consider creating a "normalized" dictionary where the values are the words from the master and the keys are their unique representations, such as sorted tuples of sub-words. If all sub-words in a word are always different, a frozenset can be used instead.

def normalize(word):
    return tuple(sorted(word.split()))
    # return frozenset(word.split())

normalized = {normalize(m) : m for m in master}
#{('1.2', 'abc', 'px'): 'abc 1.2 px', 
# ('5.4', 'pqr', 'tr'): 'pqr 5.4 tr', 
# ('1.8', 'cmq'): '1.8 cmq', ('2.5', 'pst'): 'pst 2.5'}

You can now convert each word in l1 to the normalized form and look it up in the dictionary:

[normalized.get(normalize(m), m) for m in l1]
#['abc 1.2 px', 'pqr 5.4 tr', '1.8 cmq', '1.8 cmq', 'pst 2.5', 'abc 1.2 px']

Note that if a word is not in the master, it is conveniently left unchanged.

Related