我如何在Python中使用range()?

时间:2018-03-24 19:06:14

标签: python loops range nested-loops factorial

我想使用 n 不同的变量,比如说 var {0},var {1},var {2},...,var {n-1}

我该怎么做?

for var{0} in range(n)
  for var{1} in [x for x in range(n) if x!=var{0}]:
    for var{2} in [x for x in range(n) if (x!=var{0} and x!=var{1})]:
      ...
        for var{n-1} in [x for x in range(n) if (x!=var{0} and x!=var{1} and ... and x!=var{n-2})]:

谢谢

2 个答案:

答案 0 :(得分:2)

这似乎只是range(n)

的排列
from itertools import permutations
for var in permutations(range(n)):
    # do something with var[0], var[1], ..., var[n-1]
    print var

根据文件

  

排列以字典排序顺序发出。因此,如果输入iterable被排序,则排列元组将按排序顺序生成。

我认为这意味着这将为您提供与示例中的方法相同的顺序。对于n=3,您会得到:

(0, 1, 2)
(0, 2, 1)
(1, 0, 2)
(1, 2, 0)
(2, 0, 1)
(2, 1, 0)

如果您对如何生成它感兴趣,itertools.permutations的源代码在其注释中具有等效的python代码(实际实现在C中):

def permutations(iterable, r=None):
    'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)'
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    indices = range(n)
    cycles = range(n-r+1, n+1)[::-1]
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

答案 1 :(得分:0)

在Python中你可以做到:

for i in range(n**n):
vars = [(int(i/(n**(n-j))))%n for j in range(1,n+1)]

其中vars是您想要的变种列表