返回1到n的所有组合python_如何用Python列出N个数字的所有排列组合?

itertools.permutations(iterable[, r])

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the itera

ble and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input itera

ble is sorted, the permutation tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value.

So if the input elements are unique, there will be no repeat values in each

permutation.

Roughly equivalent to:

def permutations(iterable, r=None):

# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC

# permutations(range(3)) --> 012 021 102 120 201 210

pool = tuple(iterable)

n = len(pool)

r = n if r is None else r

if r > n:

return

indices = range(n)

cycles = range(n, n-r, -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

【 在 sjtudent (Me) 的大作中提到: 】

: 多谢大侠!!! 不知用代码可否实现?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值