Using Python, find anagrams for a list of words

前端 未结 22 897
失恋的感觉
失恋的感觉 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:30

    import collections
    
    def find_anagrams(x):
        anagrams = [''.join(sorted(list(i))) for i in x]
        anagrams_counts = [item for item, count in collections.Counter(anagrams).items() if count > 1]
        return [i for i in x if ''.join(sorted(list(i))) in anagrams_counts]
    

提交回复
热议问题