0

我有两个字符串(实际上是 AQL)。有没有一种方法可以在它们之间进行比较,即使顺序不一样(我想在下面得到正确的值,因为所有值都相等)?

'items.find({"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"})'

'items.find({"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"})'
4

2 回答 2

2

这两个字符串是有效的 Pythondict文字。所以让我们将它们转换为dict对象:

a = '{"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"}'

b = '{"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"}'

import ast
a = ast.literal_eval(a)
b = ast.literal_eval(b)

...然后只是比较它们:

print(a==b)   # prints:  True
于 2019-11-26T21:28:36.797 回答
1

从...开始:

input_1 = 'items.find({"repo": "lld-test-helm", "path": "customer-customer", "name": "customer-customer-0.29.3.tgz", "type": "file"})'
input_2 = 'items.find({"name": "customer-customer-0.29.3.tgz", "path": "customer-customer", "type": "file", "repo": "lld-test-helm"})'

items.find()从字典周围剥离呼叫:

input_1 = input_1[11:-1]
input_2 = input_2[11:-1]

或者,如果您想更笼统:

input_1 = input_1[input_1.find('{'):input_1.rfind('}')+1]
input_2 = input_2[input_2.find('{'):input_2.rfind('}')+1]

至于从那一点确定两个字典字符串的相等性,必须将它们转换为实际的字典。

如果您愿意,可以使用 jez ( ast.literal_eval()) 建议的方法,尽管我个人会json.loads()为此目的使用:

import json

dict_1 = json.loads(input_1)
dict_2 = json.loads(input_2)

然后你只需比较两个字典:

dict_1 == dict_2

在这种情况下会返回True

于 2019-11-26T21:57:58.787 回答