简体   繁体   中英

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}

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

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.

I think that means this will give you the same ordering as the approach in your example. For n=3 you get:

(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):

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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