简体   繁体   中英

Understanding lambda functions in python

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]) )

how can I duplicate the lambda function as a standard custom sort function?

Do you mean this:

def sort(a, num):
  def key(x):
    return int(x[num])
  return sorted(a, reverse=True, key=key)

or perhaps this:

from functools import partial

def key(num, x):
  return int(x[num])

def sort(a, num):
  return sorted(a, reverse=True, key=partial(key, num))

?

Python provides operator.itemgetter for doing this kind of thing:

def sort(a, num):
    return sorted(a, reverse=True, key=operator.itemgetter(num))

Edit

As @NPE pointed out, that doesn't convert the key to an int for sorting. For that, you're best off to stick with a lambda.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM