Using Python, find anagrams for a list of words

前端 未结 22 871
失恋的感觉
失恋的感觉 2020-12-13 01:11

If I have a list of strings for example:

[\"car\", \"tree\", \"boy\", \"girl\", \"arc\"...]

What should I do in order to find anagrams in t

22条回答
  •  天涯浪人
    2020-12-13 01:17

    One solution is to sort the word you're searching anagrams for (for example using sorted), sort the alternative and compare those.

    So if you would be searching for anagrams of 'rac' in the list ['car', 'girl', 'tofu', 'rca'], your code could look like this:

    word = sorted('rac')
    alternatives = ['car', 'girl', 'tofu', 'rca']
    
    for alt in alternatives:
        if word == sorted(alt):
            print alt
    

提交回复
热议问题