【问题标题】:Is is possible to compare strings with different order using python3是否可以使用 python3 比较具有不同顺序的字符串
【发布时间】:2020-03-22 09:03:01
【问题描述】:

我有两个字符串(实际上是 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"})'

【问题讨论】:

  • 你如何最终得到那些带有方法被调用的字符串?
  • @eyllandesc 为什么要去掉字符串格式?
  • 你需要澄清你是否有完整的字符串,包括方法。
  • @roganjosh 它与 artifacoty AQL 有关,所以我无法真正控制我得到它的顺序
  • 这不能回答我的问题。你得到那些实际的字符串还是你自己创建它们?我已经在它变得更加混乱之前回滚了它,但是你对正在发生的事情给出了零细节

标签: python string artifactory-query-lang


【解决方案1】:

这两个字符串是有效的 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

【讨论】:

  • 你刚刚删除了items.find(),不是吗?
  • 当然。如果有人真的需要,可以提供删除这些字符的说明。
  • 嗯,他们在字符串中。
  • @jez python ast in only from python 3.8 no?有低版本的解决方案吗?
  • @arielma 你可以用 json 做类似的事情。参考:geeksforgeeks.org/…
【解决方案2】:

开始于:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2022-10-15
    • 1970-01-01
    相关资源
    最近更新 更多