2014-03-27 279 views
0

有沒有辦法在for循環中創建兩個範圍。我必須檢查讓對方說10個數組,但如果array1被選中,它不應該檢查自己。 如果選擇array1,則應使用arrays2-10檢查array1。如果選擇第二個,則應該使用array1和array3-10進行檢查。停止循環Python

我發現一個鏈函數,但它似乎並沒有在我的情況下正常工作,或者我做錯了什麼。

for i in range (1,11): 
    test_array is picked 
    for j in chain(range(1,i),range(i+1,11)): 
     does the check between test_array and all the other arrays Excluding the one picked as test_array 

for i in range(1,11): 
    pick test_array 
     for j in range (1,11): 
      if (j==i): 
       continue 
      .... 

根據測試這個和平比較陣列1與自身 上面的代碼適用於2 for循環,但我有嵌套超過3個,並繼續它去一路下來,這不是我想要 謝謝

找到我一直在尋找的答案:

for i in range(1,11): 
    do something. 
    for j in range(1,i) + range((i+1),11): 
     do something 
+0

目前尚不清楚究竟你正在尋找因爲請提供一些例子。 –

+0

我想做循環,從循環中排除某些數字。例如,如果選擇2,它應該像這樣(1,3,4,5,6,7,8,9,10)等等,希望更清楚 – user3462014

+0

爲什麼不加'if j == i:繼續'而不是? –

回答

0

使用itertools.combinations()

import itertools 
arrays = [[x] for x in 'abcd'] 
# [['a'], ['b'], ['c'], ['d']] 

for pair in itertools.combinations(arrays, 2): 
    print pair # or compare, or whatever you want to do with this pair 
0

你可以在這裏使用itertools.permutations

import itertools as IT 
from math import factorial 

lists = [[1, 2], [3,4], [4,5], [5,6]] 
n = len(lists) 
for c in IT.islice(IT.permutations(lists, n), 0, None, factorial(n-1)): 
    current = c[0] 
    rest = c[1:] 
    print current, rest 

輸出:

[1, 2] ([3, 4], [4, 5], [5, 6]) 
[3, 4] ([1, 2], [4, 5], [5, 6]) 
[4, 5] ([1, 2], [3, 4], [5, 6]) 
[5, 6] ([1, 2], [3, 4], [4, 5]) 

並採用另一種方式切片:

lists = [[1, 2], [3,4], [4,5], [5,6]] 
n = len(lists) 
for i, item in enumerate(lists): 
    rest = lists[:i] + lists[i+1:] 
    print item, rest