2017-07-14 89 views
0

我對Python很新,希望對我正在開展工作的項目有所幫助。
我有一個列表字典,並希望遍歷字典並檢查列表中的任何值是否相同。如何比較同一字典中的兩個列表,並查看兩個值是否都在

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

我需要檢查「一」的列表值和檢查,看看是否在「二」和「三化」,然後檢查「兩節」的值是在「三化」等等。然後我需要打印出相同的密鑰和值。 即。

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

不確定最好的方法來做到這一點。

+0

哦,你改變問題的陳述......像幾乎完全 –

回答

4

您可以使用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' 
+0

笑除了他完全改變了問題stateme nt(+1都是一樣的...我有幾乎相同的東西打字,但...) –

+0

謝謝你的工作很好。 – czach123

+0

@ czach123如果您覺得這個回答有用,您可以考慮接受它。 –

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

這樣做要快,因爲它是相對於組合名單從原來的字典中的總長度線性的這種方式。

0
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

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   
相關問題