我想转换以下列表:
rtt: [38,1,97]
site: ["A","B","C"]
存入字典中,例如:
dict: [ {'rtt':38, 'site':'A'},{'rtt':1, 'site':'B'},{'rtt':97,'site':'C'}]
因此我可以使用以下方法在 rtt 上对其进行排序:
x = dict | sort(attribute:'rtt')
然后按正确的顺序提取站点属性:
x | map(attribute:'site') | list
应该给出:[ 'B', 'A', 'C']
答案1
好,我知道了:
- name: create dict list variable, NICE ONE
set_fact:
SITES_DICT: "{{ SITES_DICT|default([]) + [{'site': item.1,'rtt': item.0}] }}"
with_together:
- "{{ rtt }}"
- "{{ site }}"
- debug:
msg: "{{ SITES_DICT }}"
verbosity: 1
- name: extract sites in sequence of rtt (!!)
set_fact:
sites_list: "{{ SITES_DICT | sort(attribute='rtt') | map(attribute='site') | list }}"
答案2
下面是使用 zip 获取结果的示例。它允许您在单个任务中完成所有操作,而无需中间 set_fact/registers 创建变量。
- hosts: localhost
gather_facts: no
vars:
rtt: [38,1,97]
site: ["A","B","C"]
tasks:
- debug:
msg: |
{{ site | zip(rtt) | sort(attribute='1') |
map(attribute='0') | list }}
# TASK [debug] ***************************
# ok: [localhost] => {
# "msg": [
# "B",
# "A",
# "C"
# ]
# }
- debug:
msg: |
{{ site | zip(rtt) | sort(attribute='1') }}
# TASK [debug] ***************************
# ok: [localhost] => {
# "msg": [
# [
# "B",
# 1
# ],
# [
# "A",
# 38
# ],
# [
# "C",
# 97
# ]
# ]
# }