前提是,里边的元素可能是乱序的
a = [{'key': 1, 'value': 2}, {'key': 3, 'value': 4}]
b = [{'key': 5, 'value': 6}, {'key': 1, 'value': 2}, {'key': 3, 'value': 41} ] # value 不一样的忽略掉
# 想要的结果:
c = [{'key': 5, 'value': 6}]
1
hehheh 2019-11-06 18:02:33 +08:00
把 key,val 转成 tuple,然后整个 list 打包成 set 然后 intersection
|
2
Cooky 2019-11-06 18:05:10 +08:00 via Android
两边各自合成一个字典做比较
|
3
fdppzrl 2019-11-06 18:11:30 +08:00 via Android
c.addAll(a.removeall(b))
c.addAll(b.removeall(a)) Java 大概的写法就酱 |
4
ranlan 2019-11-06 18:14:17 +08:00
b = [{'key': 5, 'value': 6}, {'key': 1, 'value': 2}, {'key': 3, 'value': 41} ]中应该是 {'key': 3, 'value': 41} 这个元素应该是 {'key': 3, 'value': 4}吧?
新手的解法 c = [i for i in b if i not in a] |
6
yesterdaysun 2019-11-06 18:32:06 +08:00
ak = set(map(lambda x: x['key'], a))
bk = set(map(lambda x: x['key'], a)) c = list(filter(lambda x: x['key'] not in bk, a)) + list(filter(lambda x: x['key'] not in ak, b)) print(c) |
7
ranlan 2019-11-06 18:35:19 +08:00
不还意思我理解错了
应该是这样 a1 = [x['key'] for x in a] c = [i for i in b if i['key'] not in a1] |
8
css3 OP |
9
johnnyluck 2019-11-06 21:46:53 +08:00
d = set([x['key'] for x in a]) ^ set([y['key'] for y in b])
c = [x for x in (a+b) if x['key'] in d] |
10
20015jjw 2019-11-07 08:11:59 +08:00 via Android
^ 双关了
|
11
xhxhx 2019-11-07 10:22:36 +08:00
array_diff
|