停止循环Python

时间:2014-03-27 09:24:03

标签: python loops for-loop nested

有没有办法在for循环中创建两个范围。我必须检查让我们说彼此之间的10个数组,但是如果选择了array1,它就不应该自己检查。 如果选择了array1,那么应该使用arrays2-10检查array1。如果选择了第二个,则应使用array1和array3-10进行检查。

我找到了一个连锁功能,但在我的情况下似乎没有正常工作或者我做错了什么。

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
             .... 
根据测试,这种和平将array1与自身进行了比较 上面的代码适用于2 for循环,但我嵌套了3个以上,并且继续它一直向下,这不是我想要的 感谢

找到我想要的答案:

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

2 个答案:

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

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