[Tutor] Python sort with a delimiter

Tom Tucker tktucker at gmail.com
Wed May 11 15:36:57 CEST 2005


Interesting!  Thank you! 


On 5/11/05, Kent Johnson <kent37 at tds.net> 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