目标是通过更改两个字符来生成具有字符串0a1b2c3d4e5
的所有可能组合
到目前为止,我掌握的代码是:
import itertools
pattern_index_zero = "xa1b2c3d4e5"
a = [['0','1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e'] if (c == 'x') else c for c in pattern_index_zero]
b = [''.join(lst) for lst in list(itertools.product(*a))]
for s in b:
print(s)
输出:
0a1b2c3d4e5
1a1b2c3d4e5
2a1b2c3d4e5
3a1b2c3d4e5
4a1b2c3d4e5
5a1b2c3d4e5
aa1b2c3d4e5
ba1b2c3d4e5
ca1b2c3d4e5
da1b2c3d4e5
ea1b2c3d4e5
它改变了第一个字符,这是可以的,但问题是我想改变第二个,第三个字符,并继续到最后一个
最终目标是生成所有可能的组合来更改字符串中的两个字符,例如:
xx1b2c3d4e5
xaxb2c3d4e5
xa1x2c3d4e5
xa1bxc3d4e5
....
xx1b2c3d4e5
0xxb2c3d4e5
0x1x2c3d4e5
0x1bxc3d4e5
如果x
可以是0,1,2,3,4,5,a,b,c,d,e
,那么在代码方面,将x
的数量增加到3甚至4有多难
EDIT用户Timus有答案。我会尽我所能去探索所有的答案,谢谢大家
您可以使用itertools.compositions来实现这一点: 因为您想交换/更改两个字符,所以我在参数中传递了2
输出 a01b2c3d4e5
1a0b2c3d4e5
ba102c3d4e5
2a1b0c3d4e5
ca1b203d4e5
3a1b2c0d4e5
da1b2c304e5
4a1b2c3d0e5
ea1b2c3d405
5a1b2c3d4e0
01ab2c3d4e5
0b1a2c3d4e5
021bac3d4e5
0c1b2a3d4e5
031b2cad4e5
0d1b2c3a4e5
041b2c3dae5
0e1b2c3d4a5
051b2c3d4ea
...
这是使用
for
循环的基本结构来解决问题。我们首先创建一个列表,其中两个索引的值将发生变化。此列表看起来有点像:[(0, 1), (0, 2), ..., (1, 0), (1, 2), ...]
,包含所有选项然后,我们迭代每一个可能的索引,我们可以更改其值
在本文中,我们还迭代了字符串的索引也可以更改为的所有值
然后检查
new_option0
是否不等于当前值,以确保没有重复项。如果没有,我们将再次迭代可能的选项-这次是为了更改第二个索引。我们再次检查new_option1
是否不等于当前值最后,我们附加编辑后的值
为了确认确实没有重复项,以下代码输出
True
:如果您想增加编辑的索引数量,我想您可以增加
for
循环和if
语句的数量。这是一个非常模块化的结构您可以从
itertools
尝试其他工具:编辑:好的,再试一次:)。这就是你想要的吗:
编辑2:如果要排除倍数,可以通过^{统一:
编辑3:我想不出你的问题,这是如何扩展到更高数量的替换。我希望你不介意我添加一个概括。这有点复杂。而且产量增长很快。因此,我没有将其打印到控制台,而是使用了一个文件(带有详细的输出)。也许你感兴趣。没问题,如果不是的话,我玩得很开心。一个问题:你需要这些东西来解决现实世界的问题吗
输出:
相关问题 更多 >
编程相关推荐