比较类型为list的python字典值,以查看它们是否按该顺序匹配 [英] compare python dictionary values of type list to see if they match in that order

查看:128
本文介绍了比较类型为list的python字典值,以查看它们是否按该顺序匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"]
}

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

I have a dictionary, and I want to compare the values (Type: List) for each key to see if they exist in that order. So essentially I'm trying to iterate over each key-value pair and compare the value which is of type list to the next value to see if the elements in that list match in that specific order. If we find a match, I want to return a list of keys that make the match.

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

ex: s1 value is a list with elements "a", "b", "c", "d", "e", so I want to check other values with the elements in the same order. So in this case key s3 would be returned since the values match with the same exact order. s1 value = s3 value because of the elements in the list match in the same order. return list would be something like [s1:s3], and multiple matches should be returned.

推荐答案

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

To find matching lists, you could do something like this:

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.)

(Note: I added s5 to prefs.)

更新

如果只需要分组的密钥,则可以通过matches.values()进行访问:

If you just want the grouped keys, you can access them via matches.values():

print(*matches.values())

哪些印刷品:

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

此外,如果您愿意,也可以将所有内容都放在一行中.

Also, you can do the whole thing in one line if you want:

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

这篇关于比较类型为list的python字典值,以查看它们是否按该顺序匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆