简体   繁体   English

了解python中的lambda函数

[英]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. 我是python的新手,我创建了一个脚本来对来自Cisco路由器的“显示ip记帐”信息进行排序。 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? 我可以使用lambda函数来做到这一点,但我的问题是如何使用标准函数复制它?

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? 所以我的问题是如何将lambda函数复制为标准的自定义排序函数? 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? 如何将lambda函数复制为标准的自定义排序函数?

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: Python提供了operator.itemgetter来做这种事情:

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. 正如@NPE指出的那样,这不会将键转换为用于排序的int For that, you're best off to stick with a lambda. 为此,您最好坚持使用lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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