我有一个 python 列表:
mylist = [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
我想遍历这些值的所有可能组合而不依赖于位置,大小为 3,这意味着我希望将这些作为迭代:
iteration: 111
iteration: 112
iteration: 113
iteration: 114
iteration: 221 # note, no 211, since the combination of these values already occured as 112
iteration: 222
iteration: 223
iteration: 224
.
.
.
Run Code Online (Sandbox Code Playgroud)
我考虑过遍历列表的唯一值,但我仍然没有找到解决这个问题的简单解决方案,我至少认为这种情况经常发生。也许有一个很好的 numpy 方法。我怎样才能做到这一点?
谢谢!
也许itertools.combinations_with_replacement是你要找的:
from itertools import combinations_with_replacement
l = [1, 2, 3, 4]
for c in combinations_with_replacement(l, 3):
print(c)
Run Code Online (Sandbox Code Playgroud)
印刷:
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
(1, 2, 4)
(1, 3, 3)
(1, 3, 4)
(1, 4, 4)
(2, 2, 2)
(2, 2, 3)
(2, 2, 4)
(2, 3, 3)
(2, 3, 4)
(2, 4, 4)
(3, 3, 3)
(3, 3, 4)
(3, 4, 4)
(4, 4, 4)
Run Code Online (Sandbox Code Playgroud)