迭代中我的嵌套循环出错?

时间:2013-02-21 18:10:43

标签: python

考虑

a = [1,2,3,4]

i = 0

j = 1

for i in range(len(a)):

       for j in range(len(a)):

          d = (a[i]-a[j])
          j = j + 1
          print i, j, d
       i = i + 1

输出

0 1 0

0 2 -1 

0 3 -2

0 4 -3

1 1 1

1 2 0

1 3 -1

1 4 -2

2 1 2

2 2 1

2 3 0

2 4 -1

3 1 3

3 2 2

3 3 1

3 4 0

我正在尝试遍历我的数组,这样我才能得到d为非零的数字,并且我不会重复相同的i和j(例如:如果i = 0,j = 1或i = 1,j = 0)。它就像做一个组合问题,我正在寻找我的数组中的对数和它的d。

3 个答案:

答案 0 :(得分:1)

只需使用permutations中的itertools

import itertools
a = [1,2,3,4]
for permutation in itertools.permutation(a, 2):
    print permutation

输出

(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
...
...

如果您还想要距离

a = [1,2,3,4]
for permutation in itertools.permutation(a, 2):
    print permutation, permutation[1] - permutation[0]

(1, 2) 1
(1, 3) 2
(1, 4) 3
(2, 1) -1

答案 1 :(得分:1)

  

我正在尝试遍历我的数组,以便我只能获得数字   d

非零

除非这是家庭作业,否则我建议您使用itertools.combinations反向排序列表或itertools.permutations来解决您的问题

>>> list((a,b) for a,b in itertools.permutations(a, 2) if a > b)
[(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
>>> list(itertools.combinations(sorted(a, reverse = True), 2))
[(4, 3), (4, 2), (4, 1), (3, 2), (3, 1), (2, 1)]

答案 2 :(得分:0)

试试这个:

a = [1,2,3,4]

i = 0

j = 1

for i in range(len(a)):

    for j in range(len(a)):

        d = (a[i]-a[j])
        j = j + 1
        if i != j and d != 0:
            print i, j, d
    i = i + 1

输出:

>>> 
0 2 -1
0 3 -2
0 4 -3
1 3 -1
1 4 -2
2 1 2
2 4 -1
3 1 3
3 2 2