问题描述
我有两个列表:
list1:
- file: f1
perm: '777'
- file: f2
perm: '677'
- file: f3
perm: '755'
- file: f4
perm: '700'
list2:
- file: f4
t_perm: '755'
- file: f3
t_perm: '677'
- file: f10
t_perm: '777'
我必须将它们合并到新列表中,如下所示:
list3:
- file: f1
perm: '777'
- file: f2
perm: '677'
- file: f3
perm: '755'
t_perm: '677'
- file: f4
perm: '700'
t_perm: '755'
正常合并是通过
- set_fact:
list3: "{{ (list1 + list2)|
groupby('file')|
map('last')|
map('combine')|
list }}"
但是我还有一个条件。如果文件存在于list1中而不存在于list2中,则合并。如果文件存在于list2中而不存在于list1中,则不要合并,请忽略该文件。
解决方法
要满足条件,我们需要从list2中删除不在list1中的项目
- “在list1中”和“不在list2中” =>合并
- “在list2中”和“不在list1中” =>不要合并
例如,intersect的文件列表并获得my_keys
。使用列表1和列表2中的文件创建my_list
,并将其用于已测试的任务set_fact
- set_fact:
list3: "{{ (list1 + my_list)|
groupby('file')|
map('last')|
map('combine')|
list }}"
vars:
my_keys: "{{ list2|map(attribute='file')|
intersect(list1|map(attribute='file'))|
list }}"
my_list: "{{ list2|selectattr('file','in',my_keys)|
list }}"
- debug:
var: list3
给予
list3:
- file: f1
perm: '777'
- file: f2
perm: '677'
- file: f3
perm: '755'
t_perm: '677'
- file: f4
perm: '700'
t_perm: '755'