比较类型列表的python字典值,看它们是否按顺序匹配

Sum*_*h M 3 python hashmap python-3.x

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"]
}
Run Code Online (Sandbox Code Playgroud)

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

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

fin*_*oot 6

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

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)
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

{('a', 'b', 'c', 'd', 'e'): ['s1', 's3'], ('c', 'd', 'e', 'b', 'e'): ['s5', 's4'], ('c', 'd', 'e', 'a', 'b'): ['s2']}
Run Code Online (Sandbox Code Playgroud)

(注意:我加入s5prefs.)


更新

如果您只想要分组键,可以通过matches.values()以下方式访问它们:

print(*matches.values())
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

['s4', 's5'] ['s1', 's3'] ['s2']
Run Code Online (Sandbox Code Playgroud)

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

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