[英]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"})'
从 dict 周围剥离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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.