请参阅我的其他解决方案,因为我认为它比这个更好:
https ://stackoverflow.com/a/10173807/1219006
>>> from operator import itemgetter
>>> from itertools import groupby
>>> data = ['1:Rammmm,mmmm', '2:surr.rrrrr', '3:Sam ttttt',
'1:qqqq qqqqqqq', '2:wwwwwwwwwww', '3:eeeeeeeee','4:tttttttt',
'1:zzzzzzzzzzzzz', '2:xxxxxxxxx']
>>> sorted_data = sorted(((int(x),y) for x,y in (el.split(':') for el in data)),key=itemgetter(0))
>>> for k,v in groupby(sorted_data,key=itemgetter(0)):
print '{' + '|'.join(text for num,text in v) + '}'
{Rammmm,mmmm|qqqq qqqqqqq|zzzzzzzzzzzzz}
{surr.rrrrr|wwwwwwwwwww|xxxxxxxxx}
{Sam ttttt|eeeeeeeee}
{tttttttt}
测试
>>> data = ['1:Rameshrrrrrrr', '2:Sureshmmmmmm', '3:Samkkkkkkkk', '1:tttttttttt', '2:wwwwwwwwwwwwwwwww', '3:yyyyyyyyy', '4:gggggggggg', '1:qqqqqqqqqqq', '2:hhhhhhhhh']
>>> sorted_data = sorted(((int(x),y) for x,y in (el.split(':') for el in data)),key=itemgetter(0))
>>> for k,v in groupby(sorted_data,key=itemgetter(0)):
print '{' + '|'.join(text for num,text in v) + '}'
{Rameshrrrrrrr|tttttttttt|qqqqqqqqqqq}
{Sureshmmmmmm|wwwwwwwwwwwwwwwww|hhhhhhhhh}
{Samkkkkkkkk|yyyyyyyyy}
{gggggggggg}