[英]Is is possible to compare strings with different order using python3
I have two strings (which are actually AQL).我有两个字符串(实际上是 AQL)。 is there a way I can compare between them even if the order is not the same (I want to get true for the below as all values are equal)?
即使顺序不同,有没有办法在它们之间进行比较(我想在下面实现,因为所有值都相等)?
'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"})'
Those two strings are valid Python dict
literals.这两个字符串是有效的 Python
dict
文字。 So let's convert them to dict
objects:因此,让我们将它们转换为
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)
...and then just compare them: ...然后只是比较它们:
print(a==b) # prints: True
Starting with:从...开始:
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"})'
Strip the items.find()
call from around the dict:从 dict 周围剥离
items.find()
调用:
input_1 = input_1[11:-1]
input_2 = input_2[11:-1]
or if you want to be more general:或者如果你想更一般:
input_1 = input_1[input_1.find('{'):input_1.rfind('}')+1]
input_2 = input_2[input_2.find('{'):input_2.rfind('}')+1]
As far as determining equality of the two dictionary strings from that point, they must be converted into actual dictionaries.至于从那时起确定两个字典字符串的相等性,它们必须转换为实际的字典。
You can use the the method suggested by jez ( ast.literal_eval()
) if you like, though I personally would use json.loads()
for this purpose:如果您愿意,您可以使用 jez (
ast.literal_eval()
) 建议的方法,但我个人会为此目的使用json.loads()
:
import json
dict_1 = json.loads(input_1)
dict_2 = json.loads(input_2)
Then you simply compare the two dictionaries:然后你只需比较两个字典:
dict_1 == dict_2
Which in this case will return True
在这种情况下将返回
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.