如何排序嵌套的IP地址列表?

时间:2017-10-28 05:29:48

标签: python sorting ip tcpdump

我有一小部分ip地址,我想根据数据包的大小(整数)对它们进行排序。我怎样才能对它们进行排序?

 mylist = [ ["176.20.100.200",176.30.100.255",230], ["176.20.100.100",176.30.100.50",24]  ["172.20.16.80",172.30.16.26",230]]

4 个答案:

答案 0 :(得分:0)

假设您的列表如下(固定拼写错误),您可以使用lambda:

排序
mylist = [["176.20.100.200","176.30.100.255",230], ["176.20.100.100","176.30.100.50",24], ["172.20.16.80","172.30.16.26",230] ]
for i,j,k in sorted(mylist, key=lambda x:x[2]):
    print ("Source : {}, Destination : {}, totalpacket : {}".format(i,j,k))

输出:

Source : 176.20.100.100, Destination : 176.30.100.50, totalpacket : 24
Source : 176.20.100.200, Destination : 176.30.100.255, totalpacket : 230
Source : 172.20.16.80, Destination : 172.30.16.26, totalpacket : 230

答案 1 :(得分:0)

在我看来,你可以这样做,这是非常pythonic:

from operator import itemgetter
mylist = [ ["176.20.100.200","176.30.100.255",230], ["176.20.100.100","176.30.100.50",24] ,["172.20.16.80","172.30.16.26",230]]
dict = {}
for index,list in enumerate(sorted(mylist, key=itemgetter(2))):
    dict[index] = {'source': list[0], 'dest': list[1], 'packetsize': list[2]  }

print(dict)

<强>输出

{0: {'source': '176.20.100.100', 'dest': '176.30.100.50', 'packetsize': 24}, 1: {'source': '176.20.100.200', 'dest': '176.30.100.255', 'packetsize': 230}, 2: {'source': '172.20.16.80', 'dest': '172.30.16.26', 'packetsize': 230}}}}

现在您将所有数据都放在一个变量中。像任何其他字典一样访问它。

注意

使用lambdas也是可能的,但在这种小情况下lambda函数会更慢。

答案 2 :(得分:0)

我想建议命名的元组。您可以将它们视为常规元组,但是当您打印它们时,您会看到每个值代表什么。

from collections import namedtuple
from operator import itemgetter

Traffic = namedtuple('Traffic', 'source destination packetsize')

mylist = [ 
        Traffic("176.20.100.200","176.30.100.255",2300),
        Traffic("176.20.100.100","176.30.100.50",24),
        Traffic("172.20.16.80","172.30.16.26",230)]

for pkt in sorted(mylist, key=itemgetter(2)):
    print(pkt)

# Traffic(source='176.20.100.100', destination='176.30.100.50', packetsize=24)
# Traffic(source='172.20.16.80', destination='172.30.16.26', packetsize=230)
# Traffic(source='176.20.100.200', destination='176.30.100.255', packetsize=2300)

答案 3 :(得分:0)

您可以使用列表理解和键一行

对其进行排序
  >>> mylist = [ ["176.20.100.200","176.30.100.255",230], ["176.20.100.100","176.30.100.50",24]  ,["172.20.16.80","172.30.16.26",230]]
   >>> sorted(mylist, key=lambda i:i[2])
[['176.20.100.100', '176.30.100.50', 24], ['176.20.100.200', '176.30.100.255', 230], ['172.20.16.80', '172.30.16.26', 230]]