gpt4 book ai didi

python - itertools 中的排列无法打印所有排列

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:29 25 4
gpt4 key购买 nike

我的问题很直接:-

在 python itertools 中,为什么我可以获得 say [,r =3] 的所有排列的打印:

>>>import itertools
>>>print list(itertools.permutations([1,2,3], 3))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

但是 [,r >3 例如 10] 只有一个空列表:

>>>print list(itertools.permutations([1,2,3], 10))
[]

有办法绕过这个吗??

最佳答案

itertools docs 中所述permutations() 不重复元素。

我想你想要combinations_with_replacement()

>>> from itertools import combinations_with_replacement

>>> print list(combinations_with_replacement([1, 2, 3], 10))

[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 2), (1, 1, 1, 1, 1, 1, 1, 1, 1, 3), (1, 1, 1, 1, 1, 1, 1, 1, 2, 2), (1, 1, 1, 1, 1, 1, 1, 1, 2, 3), (1, 1, 1, 1, 1, 1, 1, 1, 3, 3), (1, 1, 1, 1, 1, 1, 1, 2, 2, 2), (1, 1, 1, 1, 1, 1, 1, 2, 2, 3), (1, 1, 1, 1, 1, 1, 1, 2, 3, 3), (1, 1, 1, 1, 1, 1, 1, 3, 3, 3), (1, 1, 1, 1, 1, 1, 2, 2, 2, 2), (1, 1, 1, 1, 1, 1, 2, 2, 2, 3), (1, 1, 1, 1, 1, 1, 2, 2, 3, 3), (1, 1, 1, 1, 1, 1, 2, 3, 3, 3), (1, 1, 1, 1, 1, 1, 3, 3, 3, 3), (1, 1, 1, 1, 1, 2, 2, 2, 2, 2), (1, 1, 1, 1, 1, 2, 2, 2, 2, 3), (1, 1, 1, 1, 1, 2, 2, 2, 3, 3), (1, 1, 1, 1, 1, 2, 2, 3, 3, 3), (1, 1, 1, 1, 1, 2, 3, 3, 3, 3), (1, 1, 1, 1, 1, 3, 3, 3, 3, 3), (1, 1, 1, 1, 2, 2, 2, 2, 2, 2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 2, 2, 2, 2, 2, 2, 2, 2, 3), (2, 2, 2, 2, 2, 2, 2, 2, 3, 3), (2, 2, 2, 2, 2, 2, 2, 3, 3, 3), (2, 2, 2, 2, 2, 2, 3, 3, 3, 3), (2, 2, 2, 2, 2, 3, 3, 3, 3, 3), (2, 2, 2, 2, 3, 3, 3, 3, 3, 3), (2, 2, 2, 3, 3, 3, 3, 3, 3, 3), (2, 2, 3, 3, 3, 3, 3, 3, 3, 3), (2, 3, 3, 3, 3, 3, 3, 3, 3, 3), (3, 3, 3, 3, 3, 3, 3, 3, 3, 3)]

关于python - itertools 中的排列无法打印所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28988012/

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