使用For循环迭代python Dictionary并在单次迭代中使用两个值

时间:2014-09-29 15:55:58

标签: python dictionary

我有一本字典

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

由于

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以通过排序dict s值的排列来获得所需的输出顺序,例如:

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

答案 2 :(得分:-1)

  

其实我只想访问这些值,所以我使用这个函数dict.values()示例它应该像这样x = 1,y = 2这些值将被用作另一个函数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)