How to sort a list of strings on a substring

Scott scott.freemire at gmail.com
Tue Oct 6 00:27:19 CEST 2009


I create a list of logs called LogList. Here is a sample:

LogList =
["inbound tcp office 192.168.0.125 inside 10.1.0.91 88",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53"]

I want to sort the list on index 3 of each string - the first IP
Address.

I only need strings with similar, first IP's to be together. I don't
need all of the IP's to be in order. For example:
either:
SortedList =
["inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
SortedList =
["inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
etc.

would be fine.

I'm reading a lot on sort, sorted, cmp, etc. but I'm just not getting
how to use an element of a string as a "key" within a list of strings.
I'm using Python 2.6.2.

Thanks




More information about the Python-list mailing list