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
          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。

4

3 回答 3

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
于 2013-02-21T18:17:14.010 回答
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)]
于 2013-02-21T18:20:10.480 回答
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
于 2013-02-21T18:16:24.430 回答