Finding and grouping anagrams by Python

前端 未结 7 1441
無奈伤痛
無奈伤痛 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 00:51

    not a one liner but a solution...

    d = {}
    for item in input:
      s = "".join(sorted(item))
      if not d.has_key(s):
        d[s] = []
      d[s].append(item)
    input2 = d.values()
    

提交回复
热议问题