我有一个要发送到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"
]
答案 0 :(得分:2)
在sorted
上使用list
操作并使用其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']