Finding and grouping anagrams by Python

前端 未结 7 1438
無奈伤痛
無奈伤痛 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:08

    Just to simplify the previous working answer a little, so that it's more 'readable' (extracting the sorted(words....) step out:

        >>> words = ['abc', 'eat', 'face', 'cab', 'tea', 'goo']
        >>> words = sorted(words, key=sorted)
        >>> words
        ['abc', 'cab', 'face', 'eat', 'tea', 'goo']
        >>> [list(group) for key,group in groupby(words, sorted)]
        [['abc', 'cab'], ['face'], ['eat', 'tea'], ['goo']]
    

    As groupby expected the Sequence is in sorted order.

提交回复
热议问题