[Tutor] Python sort with a delimiter

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


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



More information about the Tutor mailing list