2014-09-29 189 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