I am new to python and I created a script to sort through "show ip accounting" information from a cisco router. The script reads a file and breaks up every line into a list, then it creates a list of every line. So I end up with a list of lists:
list a = [[192.168.0.1,172.16.0.1,3434,12222424],[192.168.2.1,172.12.0.1,33334,12667896722424]]
I want to be able to sort by the third column or 4th columns of the list within the list.
I was able to do it using a lambda function, but my question is how to duplicate this using a standard function?
here is my code below:
from sys import argv
script, option, filename = argv
a=[]
b=[]
def openfile(filename):
file = open(filename)
for line in file:
if not line.startswith(" "):
a.append((line.split()))
return a
def sort(a,num):
b = sorted(a, reverse=True, key=lambda x: int(x[num]))
return b
def top5(b):
print "Source Destination Packets Bytes"
for i in b[:4]:
print i[0]+" "+i[1]+" "+i[2]+" "+i[3]
def main(option):
a = openfile(filename)
if option == "--bytes":
b = sort(a,3)
top5(b)
elif option == "--packets":
b = sort(a,2)
top5(b)
else:
print """
Not a valid switch,
--bytes to sort by bytes
--packets to sort by packets."""
main(option)
So my question is how can I duplicate the lambda function as a standard custom sort function? I am trying to figure out how this works.
b = sorted(a, reverse=True, key=lambda x: int(x[num]))