Finding and grouping anagrams by Python

前端 未结 7 1532
無奈伤痛
無奈伤痛 2021-01-20 00:32
input: [\'abc\', \'cab\', \'cafe\', \'face\', \'goo\']
output: [[\'abc\', \'cab\'], [\'cafe\', \'face\'], [\'goo\']]

The problem is simple: it grou

7条回答
  •  孤城傲影
    2021-01-20 01:03

    from itertools import groupby
    
    words = ['oog', 'abc', 'cab', 'cafe', 'face', 'goo', 'foo']
    
    print [list(g) for k, g in groupby(sorted(words, key=sorted), sorted)]
    

    Result:

    [['abc', 'cab'], ['cafe', 'face'], ['foo'], ['oog', 'goo']]
    

    You can't just use the groupby function, as that only groups together sequential elements for which your key function produces the same result.

    The easy solution is just to sort the words first using the same function as you use for grouping.

提交回复
热议问题