如何比较同一字典中的两个列表,并查看两个值是否都在
我对Python很新,希望对我正在开展工作的项目有所帮助。
我有一个列表字典,并希望遍历字典并检查列表中的任何值是否相同。如何比较同一字典中的两个列表,并查看两个值是否都在
dict={'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}
我需要检查“一”的列表值和检查,看看是否在“二”和“三化”,然后检查“两节”的值是在“三化”等等。然后我需要打印出相同的密钥和值。 即。
3 - 'one' 'two'
5 - 'two' 'three'
不确定最好的方法来做到这一点。
您可以使用itertools.combinations
键的组合,并找到价值的itersection为成对密钥:
from itertools import combinations
dct = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}
for k1, k2 in combinations(dct, 2):
s = set(dct[k1]).intersection(dct[k2])
for x in s:
print("{2} - '{0}' '{1}'".format(k1, k2, x))
3 - 'one' 'two'
5 - 'two' 'three'
笑除了他完全改变了问题stateme nt(+1都是一样的...我有几乎相同的东西打字,但...) –
谢谢你的工作很好。 – czach123
@ czach123如果您觉得这个回答有用,您可以考虑接受它。 –
for v in set(sum(dict.values(), [])):
keys = [k for k in dict if v in dict[k]]
print("{:d} - {:s}".format(v, "'" + "' '".join(keys) + "'"))
一个很好的办法做到这一点在纯Python是迭代结果列表中的所有可能的值。创建一个将每个值映射到与其关联的键的字典。
d ={'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}
results = dict()
for key in d.keys():
for value in d[key]:
if value in results:
results[value].append(key)
else:
results[value] = [key]
现在,当你调用的结果,你会得到一本字典,看起来像
{1: ['one'],
2: ['one'],
3: ['two', 'one'],
4: ['two'],
5: ['three', 'two'],
6: ['three'],
7: ['three']}
然后,我们可以经历的结果,只打印出与多个相关联的密钥的人。
for number, strings in results.items():
if len(strings) > 1:
print number, strings
给你:
3 ['two', 'one']
5 ['three', 'two']
这样做要快,因为它是相对于组合名单从原来的字典中的总长度线性的这种方式。
new_data = {}
data_dict = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}
for key,values in data_dict.items():
for value in values:
new_data.setdefault(value,[]).append(key)
print new_data
我想是我怎么会做...那里有棘手和冷却器的方式,但是这很容易理解,我认为最小的大O
你可以把字典转为列表元组则 迭代列表比较第一元组剩余 元组列表如下:
data = {'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}
search = list(data.items())
while search:
target = search.pop(0)
for candidate in search:
for item in target[1]:
if item in candidate[1]:
print (item, target[0], candidate[0])
3 one two
5 two three
哦,你改变问题的陈述......像几乎完全 –