可以使用 python3 比较不同顺序的字符串
Is is possible to compare strings with different order using python3
我有两个字符串(实际上是 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"})'
这两个字符串是有效的 Python dict
文字。因此,让我们将它们转换为 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
开始于:
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
在这种情况下 return True
我有两个字符串(实际上是 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"})'
这两个字符串是有效的 Python dict
文字。因此,让我们将它们转换为 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
开始于:
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
在这种情况下 return True