471,317 Members | 2,596 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,317 software developers and data experts.

Q: listsort and dictsort - official equivalents?

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[b]): # 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[b]): # do
print key,val
# od

Am I missing some obvious standard routine?
--
Neville D - NZ
α›*αšΎα›–α›¬β€‹αš‘α›α›šα›–α›¬β€‹αš‘α›–α›šα›α›‹α› *α›–α›šαšͺα›αš’α›—α›¬β€‹αšͺα›¬β€‹α›Žα›–αš’α›‹α›¬β €‹αšΎαš°α›¬β€‹α›žα›–α›ˆαš±α›α›—αšͺᛏα›*
note: This document contains Anglo-Saxon Futhorci UTF-8 characters
from: http://junicode.sourceforge.net/ - eg αš¦α›– αš*α›αš±α›‹α› αš*αš°α›

Jun 20 '07 #1
0 891

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.