开发者

how to use python to produce a group of anagram with a given list

for example :giving a list

['car','bed','stop','pots','arc','tops','z','z','rac','deb'] 

then with the function: produce

[['arc', 'car', 'rac'], ['bed', 'deb'], ['pots', 'stop', 'tops'], ['z', 'z']] 
开发者_开发百科


Seems to be taken from this assigment, but the OP doesn't specify the "no builtin sort constraint, so...

>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> words = ['car','bed','stop','pots','arc','tops','z','z','rac','deb']
>>> for w in words:
...   d[''.join(sorted(w)].append(w)
... 
>>> d.values()
[['bed', 'deb'], ['car', 'arc', 'rac'], ['z', 'z'], ['stop', 'pots', 'tops']]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜