Q: listsort and dictsort - official equivalents?

N

Neville D

I expressed my creativity & created two routines, listsort & dictsort.

def listsort(l,cmp=None): l.sort(cmp); return l
def dictsort(d,cmp=None):return [(k,d[k])for k in listsort(d.keys(),cmp=cmp)]

Basically I am more familiar with sorting inside a for loop, eg in
bourne shell one can do "for loop sorts":

for group in $(sort /etc/group); do
echo group;
done

In python I must kick off a sort on the line before I start the
iteration. (This does make sense because at the end of the day the sort
has complete BEFORE the for loop can proceed - that is... until the day
when python lists have a secondary index ;-).

group_list=group_dict.keys()
group_list.sort()
for group in group_list: # do
print group,group_dict[group]
# done

I am sure python has a more concise way of doing this, any hints?

Cheers
NevilleD

# examples:

#!/usr/bin/env python
## -*- coding: utf-8 -*-
## purpose: demo sorting in python
def aleph_cmp(a,b): # class only needs the "<" operator
if a<b: return -1
elif b<a: return 1
else: return 0 # fi
# end aleph_cmp

def listsort(l,cmp=None): l.sort(cmp); return l # end

# example application:
mydict=dict(zip("cba",(2,1,3)))

print "a) sort by the first key using the std cmp"
for key in listsort(mydict.keys(),cmp=cmp): # do
print key,mydict[key]
# od

# if your object had a '-' operator, then you would not need to do this.
print "b) custom sort by the first key - need the '<' operator"
for key in listsort(mydict.keys(),aleph_cmp): # do
print key,mydict[key]
# od

print "c) custom sort by the second key - using the numeric '-' operator"
for key in listsort(mydict.keys(),cmp=lambda a,b: mydict[a]-mydict): # do
print key,mydict[key]
# od

# ᚠinally: I ᛒelieve listsort & dictsort aᚱe not in the ᛋtd... ᛒut ᛗayᛒ they ᚱ?
def dictsort(d,cmp=None):return [(k,d[k])for k in listsort(d.keys(),cmp=cmp)] # end

print "d) 'dictsort' sort by the second key - using the numeric '-' operator"
for key,val in dictsort(mydict,cmp=lambda a,b: mydict[a]-mydict): # do
print key,val
# od

Am I missing some obvious standard routine?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top