unittest 需要断言两个列表是一样的,但是列表中的元素是字典,而且两个列表的顺序不一样。
如何比较?
我知道 assertListEqual 是有序比较,assertSetEqual 是无序比较,但是好像无法把列表转为 set,因为列表中元素是字典类型的。
例子如下:
[{"a": "apple", "b": "banana"}, {"a": "angry", "b": "boring"}]
[{"a": "angry", "b": "boring"}, {"a": "apple", "b": "banana"}]
两个列表都 sort 再对比
可以自己写个断言方法
把 keys 和 values 都拿出来做比较,Python 字典有对应的方法
如果你是不关注顺序,只关注元素相同,那两个列表都用一样的规则排个序,再比较就好了。
@xglh0901 @chenhengjie123 谢谢,了解了!
一直纠结于 unittest 提供的固有 assert 方法,没有想到可以先对列表做处理
类似以下方法,len(list1)==0 就相同了。如果调试没过,就忽略我说的,好久没用过 python 了
list=[{"a": "apple", "b": "banana"}, {"a": "angry", "b": "boring"}]
list1=[{"a": "angry", "b": "boring"}, {"a": "apple", "b": "banana"}]
for i in list:
list1.remove(dict(i))
看下这个,随便写了下
def way(a):
n = len(a)
list3 = []
list4 = []
for i in range(0, n):
list3.extend(list(a[i].keys()))
list4.extend(list(a[i].values()))
list3.extend(list4)
return list3
list1 = [{"a": "apple", "b": "banana"}, {"a": "angry", "b": "boring"}]
list2 = [{"a": "angry", "b": "boring"}, {"a": "apple", "b": "banana"}]
k1 = way(list1)
k2 = way(list2)
if k1 == k2:
print("pass")
else:
print("fail")
这样可以么,转成字符串排序后比较
import json
print(sorted(json.dumps(a)) == sorted(json.dumps(b)))
看到标题就猜到是你提问了。
完整的用例是怎样的?
这个方法好像不太行,因为这样就把键和值分开了,如果是:
list1 = [{"a": "apple", "b": "banana"}, {"a": "angry", "b": "boring"}]
list2 = [{"a": "boring", "b": "angry"}, {"a": "apple", "b": "banana"}]
他也会以为是一样的吧
def compare_list(s, t):
t = list(t)
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t
result = compare_list(list1, list2)
assert result
Hi,try to use python DeepDiff,make sure ignore_order=True
, for example:
from deepdiff import DeepDiff
import pprint
a = {
"title": "V2EX",
"slogan": "way to explore",
"description": "创意工作者们的社区",
"domain": {
"url": "www.v2ex.com",
"host": "8080"
},
"data": [{"id":"5e4fa8531225c9423dcda9d8","author_id":"51f0f267f4963ade0e08f503","tab":"share"}, {"id":"5e16978581adfe260207a8c1","author_id":"54009f5ccd66f2eb37190485","tab":"share"}]
}
b ={
"title": "V2EX",
"slogan": "way to explore",
"description": "创意工作者们的社区",
"domain": {
"url": "www.v2ex.com",
"host": "8080"
},
"data": [{"id":"5e16978581adfe260207a8c1","author_id":"54009f5ccd66f2eb37190485","tab":"share"},{"id":"5e4fa8531225c9423dcda9d8","author_id":"51f0f267f4963ade0e08f503","tab":"share"}]
}
pprint.pprint(DeepDiff(a,b,ignore_order=True))
for your example,it also works:
from deepdiff import DeepDiff
import pprint
list1 = [{"a": "apple", "b": "banana"}, {"a": "angry", "b": "boring"}]
list2 = [{"a": "boring", "b": "angry"}, {"a": "apple", "b": "banana"}]
pprint.pprint(DeepDiff(list1,list2,ignore_order=True))