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类型的值与下一个值进行比较,以查看该列表中的元素是否按特定顺序匹配。如果找到匹配项,我想返回进行匹配的键列表。
ex:s1值是一个包含元素“ a”,“ b”,“ c”,“ d”,“ e”的列表,因此我想按相同顺序检查其他值。因此,在这种情况下,将返回键s3,因为这些值以相同的确切顺序匹配。 s1值= s3值,因为列表中的元素以相同顺序匹配。 返回列表类似于[s1:s3],并且应该返回多个匹配项。
答案 0 :(得分:6)
要查找匹配列表,您可以执行以下操作:
{"packet":01,"reporting time":1500, "altitude":6500,"latitude":0,"longitude": 0,"ballast":34,"parachute":0}
哪些印刷品:
f5fk43d2
(注意:我在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']}
。)
更新
如果只需要分组的密钥,则可以通过s5
访问它们:
prefs
哪些印刷品:
matches.values()
此外,如果您愿意,也可以将所有操作都放在一行中。
print(*matches.values())
答案 1 :(得分: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']}