如何比较两个dict
列表?结果应该是dict B列表中的奇数项
示例:
ldA = [{'user':"nameA", 'a':7.6, 'b':100.0, 'c':45.5, 'd':48.9},
{'user':"nameB", 'a':46.7, 'b':67.3, 'c':0.0, 'd':5.5}]
ldB =[{'user':"nameA", 'a':7.6, 'b':99.9, 'c':45.5, 'd':43.7},
{'user':"nameB", 'a':67.7, 'b':67.3, 'c':1.1, 'd':5.5},
{'user':"nameC", 'a':89.9, 'b':77.3, 'c':2.2, 'd':6.5}]
这里我想比较一下ldA和ldB。它应该打印下面的输出。
ldB -> {user:"nameA", b:99.9, d:43.7}
ldB -> {user:"nameB", a:67.7, c:1.1 }
ldb -> {user:"nameC", a:89.9, b:77.3, c:2.2, d:6.5}
我已经完成了下面的链接,但是在那里它只返回名称,但是我想要上面那样的名称和值。
List of Dicts comparision to match between lists and detect value changes in Python
我的方法:基于要排除的值的ldA构建一个查找,然后确定从ldB中的每个列表中排除适当值的结果。
You should, however, be aware that comparing floating-point values like that can't be relied upon。
我假设对应的
dict
在两个列表中的顺序相同。在这种假设下,您可以使用以下代码:
未经测试。如果有错误请评论,我会改正的
对于一般解决方案,请考虑以下内容。即使用户在列表中无序,它也会正确地进行区分。
然后,您可以检查解决方案:
相关问题 更多 >
编程相关推荐