如何通过使用python或regex忽略两个索引来比较两个字符串

问题描述 投票:0回答:1

语言: Python 3。

我很想知道如何通过忽略对象“ DateandTime”的值来比较以下字符串,因为它永远不会相同。因此,在比较过程中,仅此一项就可以忽略。

Str1='''{"Name":"Denu","Contact":12345678, "DateandTime":20200207202019}'''

Str2= '''{"Name":"Denu","Contact":12345678, "DateandTime":20200207220360}'''

任何帮助都将不胜感激。

python regex string-comparison
1个回答
0
投票

首先,您可以轻松地使用字典创建相同的功能。不要将其转换为字符串,因为它已经是可用的对象。

Str1 = {"Name":"Denu","Contact":12345678, "DateandTime":20200207202019}
Str2 = {"Name":"Denu", "Contact":12345678, "DateandTime":20200207220360}

def isidentical(dct1, dct2):
    """ Compares two dicts for equality """

    ignore = ["DateandTime"]

    keys1 = set(key for key in dct1 if not key in ignore)
    keys2 = set(key for key in dct2 if not key in ignore)

    if keys1 != keys2:
        return False

    for key in keys1:
        if dct1[key] != dct2[key]:
            return False
    return True

x = isidentical(Str1, Str2)
print(x)
# True in this case

如果一个字典的键号不同于另一个,或者值不相同,则会抛出错误。显然,您可以扩展ignore列表。


0
投票

您可以检查allexcept是否与您所关心的键相等:

all

此打印def eq(d1, d2): return all(d1.get(k) == d2.get(k) for k in d1.keys() if k != "DateandTime") d1 = {"Name": "Denu", "Contact": 12345678, "DateandTime": 20200207202019} d2 = {"Name": "Denu", "Contact": 12345678, "DateandTime": 20200207220360} print(eq(d1, d2))

© www.soinside.com 2019 - 2024. All rights reserved.