2013-02-21 72 views
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是非零數字和我不走了同樣的我和j(例如:如果i = 0,j = 1或i = 1,j = 0)。它就像做一個組合問題,我正在查看我的數組中的對的數量和d的數量。

+0

你有問題嗎? – 2013-02-21 18:14:07

+1

另外,'i = 0'和'j = 0'什麼也不做。遍歷'for i in range(len(a))'開始'i'爲0.並且迭代'for範圍內的len(len(a))'開始'j'爲0.要從'j = 1'到'len(a)',do:'爲範圍內的j(1,len(a))'。 – 2013-02-21 18:20:33

回答

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 
1

只需使用permutationsitertools

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 
+0

謝謝!實際上,使用itertools的組合正是我所期待的。這讓我想起了它。 – user1821176 2013-02-21 18:43:20

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)]