排序具有不同格式的IP地址

时间:2018-10-05 01:09:39

标签: python sorting

我正在尝试获取:

['192.168.70.19 (tcp/1433)']
['192.168.70.223 (tcp/1051),192.168.70.19 (tcp/1025), 192.168.70.245 (tcp/1051)'] 
['192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']

['192.168.70.19 (tcp/1433)']
['192.168.70.19 (tcp/1025),192.168.70.223 (tcp/1051), 192.168.70.245 (tcp/1051)'] 
['192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']

这是我的代码,不正确。由于想要保留tcp部分,我无法对IP地址进行排序。有谁对此有更好的建议或解决方案。任何想法将不胜感激。

import re
a=['192.168.70.19 (tcp/1433)', '192.168.70.223 (tcp/1051),192.168.70.19 (tcp/1025),192.168.70.245 (tcp/1025)', '192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']


for z in a:
    if z.find(','):
        #removes tcp part (but I want to keep)        
        #b = re.sub(r'\(.*?\)', '', z)

        #I can sort the IP with this, but it doesnt have the tcp part.
        #z.sort(key=lambda s: map(int, s.split('(')[0].split('.')))

2 个答案:

答案 0 :(得分:-1)

这是不使用正则表达式的解决方案

string = 'Weird string case'
result = ''
i=0
for m in string:
    if(m==' '):
       result = result + m
       i=0
    elif(i%2==0):
       result = result+m.upper()
       i+=1
    else:
       result = result + m.lower()
       i+=1
    print(result)

要对IP + TCP组合进行排序,请使用该元组的第一部分对ip addr进行排序

输出:

[','.join(sorted(x.split(','), key= lambda x: x.split()[0])) for x in a]

答案 1 :(得分:-1)

您可以使用以下列表理解:

[','.join(sorted(i.split(','), key=lambda s: tuple(map(int, s.split()[0].split('.'))))) for i in a]

,以便使用以下输入(请注意,我已将示例输入中的192.168.70.19更改为192.168.70.39,以演示IP地址是按数字排序的):

a=['192.168.70.19 (tcp/1433)',
   '192.168.70.223 (tcp/1051),192.168.70.39 (tcp/1025),192.168.70.245 (tcp/1025)',
   '192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']

上面的列表理解将返回:

['192.168.70.19 (tcp/1433)',
 '192.168.70.39 (tcp/1025),192.168.70.223 (tcp/1051),192.168.70.245 (tcp/1025)', 
 '192.168.70.19 (tcp/3389),192.168.70.223 (tcp/3389)']`