python - 如何选择任何有序的三个算术运算符组,允许替换?

标签 python cartesian-product

<分区>

我需要创建三个算术运算符(+、-、*、/)的所有可能序列。

对于列表 operators = ['+', '-', '*', '/'],我尝试使用 list(itertools.combinations_with_replacement(operators ,3)) ,它返回这个列表:

[('+', '+', '+'), ('+', '+', '-'), ('+', '+', '/'), ('+', '+', '*'), ('+', '-', '-'), ('+', '-', '/'), ('+', '-', '*'), ('+', '/', '/'), ('+', '/', '*'), ('+', '*', '*'), ('-', '-', '-'), ('-', '-', '/'), ('-', '-', '*'), ('-', '/', '/'), ('-', '/', '*'), ('-', '*', '*'), ('/', '/', '/'), ('/', '/', '*'), ('/', '*', '*'), ('*', '*', '*')]

问题是我还需要像 ('*', '+', '*') 这样的组合,但它们不包括在内。我也尝试过 itertools.permutations(operators, 3),但在这种情况下,运算符不会重复。

我怎样才能得到所有想要的结果?

最佳答案

这就是itertools.product用于:

<b>from itertools import product</b>

result = list(<b>product(</b>operators<b>,repeat=3)</b>)

这个构造:

>>> list(product(operators,repeat=3))
[('+', '+', '+'), ('+', '+', '-'), ('+', '+', '*'), ('+', '+', '/'), ('+', '-', '+'), ('+', '-', '-'), ('+', '-', '*'), ('+', '-', '/'), ('+', '*', '+'), ('+', '*', '-'), ('+', '*', '*'), ('+', '*', '/'), ('+', '/', '+'), ('+', '/', '-'), ('+', '/', '*'), ('+', '/', '/'), ('-', '+', '+'), ('-', '+', '-'), ('-', '+', '*'), ('-', '+', '/'), ('-', '-', '+'), ('-', '-', '-'), ('-', '-', '*'), ('-', '-', '/'), ('-', '*', '+'), ('-', '*', '-'), ('-', '*', '*'), ('-', '*', '/'), ('-', '/', '+'), ('-', '/', '-'), ('-', '/', '*'), ('-', '/', '/'), ('*', '+', '+'), ('*', '+', '-'), <b>('*', '+', '*')</b>, ('*', '+', '/'), ('*', '-', '+'), ('*', '-', '-'), ('*', '-', '*'), ('*', '-', '/'), ('*', '*', '+'), ('*', '*', '-'), ('*', '*', '*'), ('*', '*', '/'), ('*', '/', '+'), ('*', '/', '-'), ('*', '/', '*'), ('*', '/', '/'), ('/', '+', '+'), ('/', '+', '-'), ('/', '+', '*'), ('/', '+', '/'), ('/', '-', '+'), ('/', '-', '-'), ('/', '-', '*'), ('/', '-', '/'), ('/', '*', '+'), ('/', '*', '-'), ('/', '*', '*'), ('/', '*', '/'), ('/', '/', '+'), ('/', '/', '-'), ('/', '/', '*'), ('/', '/', '/')]

关于python - 如何选择任何有序的三个算术运算符组,允许替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43390351/

相关文章:

java - 从笛卡尔积中获取不同记录的算法

algorithm - 集合的组合/笛卡尔积的计算(无重复且无顺序限制)

python - 运行全新安装的 iPython 时出错

python - 如何将命令的输出复制到文件?

python - 引用同一行中的单元格

Mysql where 子句中的笛卡尔积

python - 从 astropy Distance 对象访问浮点值

python - 使用 Run with Friends fb 应用程序的图片属性格式

c - 如何在C中生成数组与其自身的笛卡尔积?

dictionary - Racket 映射笛卡尔积事物