我正在尝试比较两个列表以找出差异和重复项。例子:
- name: Debug
hosts: "localhost"
gather_facts: no
connection: local
vars:
list1:
- {name: aBC_SOMEITEM-A01_dEF, type: random, policy: one}
- {name: aBC_SOMEITEM-A02_dEF, type: random, policy: two}
- {name: aBC_SOMEITEM-A03_dEF, type: random, policy: three}
list2:
- {name: "SOMEITEM-A01", type: "random", policy: "one"}
- {name: "SOMEITEM-A02", type: "random", policy: "two"}
- {name: "SOMEITEM-A03", type: "random", policy: "three"}
- {name: "SOMEITEM-A03", type: "random", policy: "three"}
- {name: "SOMEITEM-A04", type: "random", policy: "four"}
list3: "{{ list1 | map('ansible.builtin.regex_replace', 'aBC_|_dEF', '') | list }}"
tasks:
- debug:
msg: |
{{ list1 | to_yaml(default_flow_style=none) }}
{{ list2 | to_yaml(default_flow_style=none) }}
{{ list3 | to_yaml(default_flow_style=none) }}
{{ list2 | difference(list3) | to_yaml(default_flow_style=none) }}
list3
过滤器后的输出map('regex_replace')
如下所示:
['{''name'': ''SOMEITEM-A01'', ''type'': ''random'', ''policy'': ''one''}', '{''name'':
''SOMEITEM-A02'', ''type'': ''random'', ''policy'': ''two''}', '{''name'': ''SOMEITEM-A03'',
''type'': ''random'', ''policy'': ''three''}']
- 如何规范化 list3 以使差异的结果输出为
- {name: SOMEITEM-A04, policy: three, type: random}
list2
有重复的字典,我怎样才能找到重复的?例如
- {name: "SOMEITEM-A03", type: "random", policy: "three"}
我从这里查看了两个答案,但无法弄清楚 - Ansible: How to getlicate items from list?
(我不介意编写自定义过滤器插件来完成此任务,因为数据集可能非常大)