简体   繁体   English

如何在Python中执行range()?

[英]How do I do n range() in Python?

I want to use n different variables, let's say var{0}, var{1}, var{2}, ..., var{n-1} 我想使用n个不同的变量,比如说var {0},var {1},var {2},...,var {n-1}

How can I do this ? 我怎样才能做到这一点 ?

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

Thank you 谢谢

It seems like this is just permutations of range(n) : 似乎这只是range(n)排列:

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

According to the documentation 根据文档

Permutations are emitted in lexicographic sort order. 排列以字典顺序排序。 So, if the input iterable is sorted, the permutation tuples will be produced in sorted order. 因此,如果对输入的iterable进行排序,则将按排序顺序生成置换元组。

I think that means this will give you the same ordering as the approach in your example. 我认为这将为您提供与示例中的方法相同的排序。 For n=3 you get: 对于n=3您将获得:

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

If you are interested in how this is being generated, the source for itertools.permutations has the equivalent python code in its comments (the actual implementation is in C): 如果您对它的生成方式感兴趣,那么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

in Python you can do: 在Python中,您可以执行以下操作:

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

where vars is the list of vars you want vars是您想要的var列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM