我有要发送到杜松路由器的命令列表。我如何在命令末尾按IP地址对列表进行排序?
从此生成set_fact和_items
生成"command_list": [
"show bgp neighbor 1.1.1.1",
"show bgp neighbor 2.2.2.2",
"show bgp neighbor 3.3.3.3",
"show route receive-protocol bgp 1.1.1.1",
"show route receive-protocol bgp 2.2.2.2",
"show route receive-protocol bgp 3.3.3.3",
"show route advertising-protocol bgp 1.1.1.1",
"show route advertising-protocol bgp 2.2.2.2"
"show route advertising-protocol bgp 3.3.3.3"
]
,由目标IP订购。
"command_list": [
"show bgp neighbor 1.1.1.1",
"show route receive-protocol bgp 1.1.1.1",
"show route advertising-protocol bgp 1.1.1.1",
"show bgp neighbor 2.2.2.2",
"show route receive-protocol bgp 2.2.2.2",
"show route advertising-protocol bgp 2.2.2.2"
"show bgp neighbor 3.3.3.3",
"show route receive-protocol bgp 3.3.3.3",
"show route advertising-protocol bgp 3.3.3.3"
]
在list
上使用sorted
操作,并利用其key
参数在进行比较之前指定要在每个列表元素上调用的函数。
command_list = [
"show bgp neighbor 1.1.1.1",
"show bgp neighbor 2.2.2.2",
"show bgp neighbor 3.3.3.3",
"show route receive-protocol bgp 1.1.1.1",
"show route receive-protocol bgp 2.2.2.2",
"show route receive-protocol bgp 3.3.3.3",
"show route advertising-protocol bgp 1.1.1.1",
"show route advertising-protocol bgp 2.2.2.2",
"show route advertising-protocol bgp 3.3.3.3"
]
def last(a):
for i in reversed(a.split()):
return i
print(sorted(command_list, key=last))
输出:
['show bgp neighbor 1.1.1.1',
'show route receive-protocol bgp 1.1.1.1',
'show route advertising-protocol bgp 1.1.1.1',
'show bgp neighbor 2.2.2.2',
'show route receive-protocol bgp 2.2.2.2',
'show route advertising-protocol bgp 2.2.2.2',
'show bgp neighbor 3.3.3.3',
'show route receive-protocol bgp 3.3.3.3',
'show route advertising-protocol bgp 3.3.3.3']