Tuesday, May 24, 2011

python: compare a list of list by list len

http://wiki.python.org/moin/HowTo/Sorting/#The_Old_Way_Using_the_cmp_Parameter



loop = []
loop.append((1,2))
loop.append((1,2,3,4,5))
loop.append((1,2,3))

def cmpfunc(x,y):
return len(x)-len(y)


loop.sort(cmp=cmpfunc)
print loop

Output:
[(1, 2), (1, 2, 3), (1, 2, 3, 4, 5)]

No comments:

Related Posts Plugin for WordPress, Blogger...