Python使用itertools查找所有组合/排列(带替换)
我确定这是我错过的重点。简单代码:
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 位的所有可能方法 - 顺序很重要。就我而言,由于 557 具有相同的数字,因此不会返回 755。
我正在寻找: ['222','223','232' (new), '225', 252' (new) ] 等
目前,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)