gpt4 book ai didi

python - 如何在 Python 中执行 n range() ?

转载 作者:行者123 更新时间:2023-12-01 02:02:22 25 4
gpt4 key购买 nike

我想使用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})]:

谢谢

最佳答案

看起来这只是 range(n) 的排列:

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

根据文档

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

我认为这意味着这将为您提供与示例中的方法相同的顺序。对于 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

关于python - 如何在 Python 中执行 n range() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com