[英]Remove common dictionary elements that are in 2 lists
I am trying to 'minus' out the common elements within 2 lists, however the elements within the 2 lists are dictionary. 我正在尝试“减去”两个列表中的公共元素,但是两个列表中的元素是字典。
Example: 例:
list_dict_01 = [{'aaa':123}, {'bbb':234}, {'ccc':234}, {'ddd':456}]
list_dict_02 = [{'bbb':234}, {'ddd':456}]
res = list(set(list_dict_01)^set(list_dict_02))
# Expected output : `[{'aaa':123}, {'ccc':234}]`
However as I execute the code, I got the following errors: 但是,当我执行代码时,出现以下错误:
# Error: unhashable type: 'dict'
# Traceback (most recent call last):
# File "<maya console>", line 4, in <module>
# TypeError: unhashable type: 'dict' #
What other ways can I do to achieve the result I wanted? 我还能采取什么其他方式来获得想要的结果?
这有效
[item for item in list_dict_01 if not item in list_dict_02]+[item for item in list_dict_02 if not item in list_dict_01]
It is the same as the first answer suggested, with the use of filter
function: 它与建议的第一个答案相同,只是使用了
filter
功能:
list_dict_01 = [{'aaa':123}, {'bbb':234}, {'ccc':234}, {'ddd':456}]
list_dict_02 = [{'bbb':234}, {'ddd':456}]
res = list(filter(lambda i: not i in list_dict_01, list_dict_02)) + list(filter(lambda i: not i in list_dict_02, list_dict_01))
print(res)
Output: 输出:
[{'aaa': 123}, {'ccc': 234}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.