我需要创建三个算术运算符(+、-、*、/)的所有可能序列。
对于列表 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>, ('*', '+', '/'), ('*', '-', '+'), ('*', '-', '-'), ('*', '-', '*'), ('*', '-', '/'), ('*', '*', '+'), ('*', '*', '-'), ('*', '*', '*'), ('*', '*', '/'), ('*', '/', '+'), ('*', '/', '-'), ('*', '/', '*'), ('*', '/', '/'), ('/', '+', '+'), ('/', '+', '-'), ('/', '+', '*'), ('/', '+', '/'), ('/', '-', '+'), ('/', '-', '-'), ('/', '-', '*'), ('/', '-', '/'), ('/', '*', '+'), ('/', '*', '-'), ('/', '*', '*'), ('/', '*', '/'), ('/', '/', '+'), ('/', '/', '-'), ('/', '/', '*'), ('/', '/', '/')]