我正在尝试比较两个列表以找出差异和重复项。例子:
- 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?
(我不介意编写自定义过滤器插件来完成此任务,因为数据集可能非常大)
创建姓名列表
给出
更新列表1
给出
使用unique过滤器从list2中删除重复项。然后,使用过滤器差异来删除共同的项目
给你想要的
用于测试的完整剧本示例
问:“list2 有一个重复的字典,我怎样才能找到重复的?”
答:计算频率。例如,
给出