我有一个要发送到 Juniper 路由器的命令列表。如何按命令末尾的 IP 地址对列表进行排序?
由此,用 set_fact 和 with_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']
