【问题标题】:compare python dictionary values of type list to see if they match in that order比较 list 类型的 python 字典值以查看它们是否按该顺序匹配
【发布时间】:2019-05-24 09:24:34
【问题描述】:
prefs = 
{
    's1': ["a", "b", "c", "d", "e"],
    's2': ["c", "d", "e", "a", "b"],
    's3': ["a", "b", "c", "d", "e"],
    's4': ["c", "d", "e", "b", "e"]
}

我有一本字典,我想比较每个键的值(类型:列表)以查看它们是否按该顺序存在。所以基本上我正在尝试迭代每个键值对并将列表类型的值与下一个值进行比较,以查看该列表中的元素是否以该特定顺序匹配。如果我们找到匹配项,我想返回一个匹配项的列表。

ex: s1 值是一个包含元素“a”、“b”、“c”、“d”、“e”的列表,所以我想用相同的顺序检查元素的其他值。所以在这种情况下,键 s3 将被返回,因为值与相同的确切顺序匹配。 s1 值 = s3 值,因为列表中的元素以相同的顺序匹配。 返回列表类似于 [s1:s3],并且应该返回多个匹配项。

【问题讨论】:

    标签: python python-3.x hashmap


    【解决方案1】:

    首先使用sorted按值排序,然后使用itertools.groupby

    prefs = {
                's1': ["a", "b", "c", "d", "e"],
                's2': ["c", "d", "e", "a", "b"],
                's3': ["a", "b", "c", "d", "e"],
                's4': ["c", "d", "e", "b", "e"],
                's5': ["c", "d", "e", "a", "b"]
            }
    
    from itertools import groupby
    [[t[0] for t in g] for k,g in groupby(sorted(prefs.items(), key=lambda x:x[1]), lambda x:x[1])]
    #[['s1', 's3'], ['s2', 's5'], ['s4']]
    

    使用值打印:

    {tuple(k):[t[0] for t in g] for k,g in groupby(sorted(prefs.items(), key=lambda x:x[1]), lambda x:x[1])}
    

    输出:

    {('a', 'b', 'c', 'd', 'e'): ['s1', 's3'],
     ('c', 'd', 'e', 'a', 'b'): ['s2', 's5'],
     ('c', 'd', 'e', 'b', 'e'): ['s4']}
    

    【讨论】:

    • @Transhuman 你如何打印这些值。我正在尝试弄清楚如何将其打印到控制台上。
    【解决方案2】:

    要查找匹配列表,您可以执行以下操作:

    prefs = {
        's1': ["a", "b", "c", "d", "e"],
        's2': ["c", "d", "e", "a", "b"],
        's3': ["a", "b", "c", "d", "e"],
        's4': ["c", "d", "e", "b", "e"],
        's5': ["c", "d", "e", "b", "e"]
    }
    
    matches = {}
    for key, value in prefs.items():
        value = tuple(value)
        if value not in matches:
            matches[value] = []
        matches[value].append(key)
    
    print(matches)
    

    哪些打印:

    {('a', 'b', 'c', 'd', 'e'): ['s1', 's3'], ('c', 'd', 'e', 'b', 'e'): ['s5', 's4'], ('c', 'd', 'e', 'a', 'b'): ['s2']}
    

    (注意:我在prefs 中添加了s5。)


    更新

    如果您只想要分组密钥,您可以通过matches.values() 访问它们:

    print(*matches.values())
    

    哪些打印:

    ['s4', 's5'] ['s1', 's3'] ['s2']
    

    此外,如果您愿意,您可以在一行中完成所有操作:

    print({value: [key for key in prefs if tuple(prefs[key]) == value] for value in set(map(tuple, prefs.values()))})
    

    【讨论】:

    • 所以 s2 被返回但它没有匹配,我是否只是假设如果一个列表没有返回 2 个键,那么它没有匹配。
    • 有道理。但是在 if 条件之后我很难遵循。所以基本上你创建了一个新的哈希并将值转换为一个元组。然后检查匹配项中是否不存在该值{}。但是在那条线之后我有点迷路了。您将值设置为空数组,但您能否在 if 之后解释这些行。如果有多个匹配项,我如何验证代码到哪里,我将 2 个键作为一组返回,而不是只返回列表中的所有键。
    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多