停止使用循环Python

2024-05-15 14:34:06 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在for循环中设置两个范围。我要检查10个数组,但是如果array1被选中,它就不应该检查它自己。 如果选择了array1,则array1应使用arrays2-10进行检查。如果选择第二个,则应使用阵列1和阵列3-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个以上的循环,并且随着continue的继续,它一直向下运行,这不是我想要的 谢谢

找到了我想要的答案:

^{pr2}$

Tags: the函数intestforrange数组array
2条回答

您可以在此处使用^{}

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

输出:

^{pr2}$

另一种使用切片的方法:

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

使用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

相关问题 更多 >