我确定我没有捕获要点。简单代码:
from itertools import combinations_with_replacement
p1 = combinations_with_replacement("2357",3)
y = [''.join(i) for i in p1]
print (y)
产生:['222', '223', '225', '227', '233', '235', '237', '255', '257', '277', '333', '335', '337', '355', '357', '377', '555', '557', '577', '777']
我正在寻找从 4 位数字中提取 3 的所有可能方法 - 其中顺序很重要。在我的例子中,不会返回 755,因为 557 具有相同的数字。
我正在寻找: ['222','223','232'(新),'225', 252'(新)]等
目前使用 combinations_with_replacement 会拒绝先前绘制数字的序列。我可能需要似乎缺少的“排列”(但带有替换)。
我忽略了什么?
干杯
最佳答案
使用itertools.product
因为您似乎在寻找整个笛卡尔积 pool X pool X pool
:
from itertools import product
p1 = product("2357", repeat=3)
y = [*map(''.join, p1)]
print(y)
关于Python 使用 itertools 查找所有组合/排列(带替换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68665316/