[Tutor] Python sort with a delimiter

Kent Johnson kent37 at tds.net
Wed May 11 15:42:27 CEST 2005


A more direct approach is to write a helper function that extracts the desired data from a field, 
and use that as the sort key:

hostnames = '''sys01-xxx-austin-tx
sys02-xxx-austin-tx
sys01-xxx-newark-oh
sys01-yyy-newark-oh
sys01-yyy-austin-tx
sys01-zzz-newark-oh
sys02-zzz-newark-oh'''.split()

def getCity(hostName):
     return hostName.split('-', 2)[-1]

hostnames.sort(key=getCity)
for line in hostnames:
     print line

Kent

Kent Johnson wrote:
> Tom Tucker wrote:
> 
>>Good morning!  Does Python have a sort function thats supports a delimiter?  
>>For example, I want to sort the below hostnames, based on the city.   
> 
> 
> This is easy to do in Python but you have to break it up into a few steps - Python's sort doesn't 
> know how to find fields but you can break the text into fields yourself, then sort on the desired 
> field. Here is one way:
> 
> import operator
> 
> hostnames = '''sys01-xxx-austin-tx
> sys02-xxx-austin-tx
> sys01-xxx-newark-oh
> sys01-yyy-newark-oh
> sys01-yyy-austin-tx
> sys01-zzz-newark-oh
> sys02-zzz-newark-oh'''.split()
> 
> # Create a list of field lists by splitting on the first two '-'
> fieldData = [ line.split('-', 2) for line in hostnames ]
> 
> # The key parameter must be a function that returns the key
> # value from a list item.
> # operator.itemgetter creates a function that accesses the desired index
> fieldData.sort(key=operator.itemgetter(2))
> 
> # Put the fields back together and print
> for line in fieldData:
>      print '-'.join(line)
> 
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list