我有一个要发送到 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']
关于python - Ansible - 按最后一个参数(IP 地址)对命令列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911108/