2014-09-29 112 views
-1

具有兩個值I有一個字典迭代蟒字典使用For循環,並在單次迭代

Example: dict = {'one':1 ,'two':2 , 'three':3} 

我想使用/的for循環單次迭代內有兩個值。最終結果應該是這樣的

# 1 2 (First iteration) 
# 1 3 (Second iteration) 
# 2 1 
# 2 3 
# 3 1 
# 3 2 

有人可以告訴我如何可以在Python字典中實現這一點。

for i in dict.values(): 

    # how do i Access two values in single iteration and to have result like mentioned  above 

感謝

+0

我覺得我的字典問題涉及必須有辦法 – Thomsan 2014-09-29 16:07:38

+1

什麼是'dict.values()'區別? – 2014-09-29 16:08:14

+0

其實我只想訪問這個值,所以我使用這個函數dict.values()例子它應該是這樣的x = 1,y = 2這些值將被用作另一個函數的參數self.funct(x, y) – Thomsan 2014-09-29 16:15:08

回答

1
import itertools 
d = {'one':1 ,'two':2 , 'three':3} 
l = list(itertools.permutations(d.values(),2)) 

>>> l 
[(3, 2), 
(3, 1), 
(2, 3), 
(2, 1), 
(1, 3), 
(1, 2)] 

for x, y in l: 
    # do stuff with x and y 
+0

請注意,python字典是無序的。如果訂單很重要,您可能需要使用OrderedDict,或者只是一個列表。 – OrionMelt 2014-09-29 16:02:21

+0

請注意,'.keys()'在這裏不是必需的... – 2014-09-29 16:02:43

+0

OP要的值,所以鍵是不相關的 – 2014-09-29 16:07:14

0

您可以通過訂購dict價值觀的排列,如獲得所需的輸出順序:

from itertools import permutations 

dct = {'one':1 ,'two':2 , 'three':3} 
for fst, snd in sorted(permutations(dct.itervalues(), 2)): 
    print fst, snd # or whatever 
-1

其實我要訪問的值只有這樣我使用這個函數dict.values()例子它應該是這樣x = 1,y = 2這些值將被用作另一個f的參數聯繫self.funct(x,y)

在您的評論中,似乎你只是想要另一個功能的兩個數字。如果你不介意的嵌套循環,這應該足夠了:

d = {'one':1 ,'two':2 , 'three':3} 
dvals = sorted(d.values() 

for x in dvals: 
    for y in dvals: 
    if x != y: 
     self.funct(x,y) 
+0

-1是不回答「在一次迭代中有兩個值」,問題的一部分是正確的?從他的評論看來,Thomsan修改了他的目標。如果還有另外一個原因 - 即循環或迭代工具以外的更好方法,請告訴我。 – Tai 2014-09-29 16:44:40