Finding and grouping anagrams by Python

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

    the unreadable, one-line solution:

    >>> import itertools
    >>> input = ['abc', 'face', 'goo', 'cab', 'cafe']
    >>> [list(group) for key,group in itertools.groupby(sorted(input, key=sorted), sorted)]
    [['abc', 'cab'], ['cafe', 'face'], ['goo']]
    

    (well, it is really 2 lines if you count the import...)

提交回复
热议问题