如何比较同一个字典中的两个列表,看两个值是否相同

时间:2017-07-14 19:56:34

标签: python

我对Python很陌生,并且非常感谢我为工作的项目提供一些帮助 我有一个列表字典,想要遍历字典并检查列表的任何值是否相同。

dict={'one':[1,2,3], 'two':[3,4,5], 'three':[5,6,7]}

我需要查看一个'一个'的列表值。并检查是否有两个'和'三',然后检查'两个'价值在三个'等等。然后我需要打印出相同的键和值。 即

3 - 'one' 'two'
5 - 'two' 'three'

不确定最好的方法。

5 个答案:

答案 0 :(得分:4)

您可以使用itertools.combinations获取密钥组合,并找到成对密钥的值的隐藏值:

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'

答案 1 :(得分:1)

在纯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']

这种做法应该很快,因为它与原始字典中组合列表的总长度成线性关系。

答案 2 :(得分:0)

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) + "'"))

答案 3 :(得分:0)

notifyDataSetChanged

我想我是怎么做到的......这种方法比较棘手,但是这很容易理解,而且我觉得最小的大O

答案 4 :(得分:0)

然后您可以将字典转换为元组列表 迭代地将列表中的第一个元组与 列表中剩余的元组如下:

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        
相关问题