【问题标题】:Combinations of elements in list in Python 3.xPython 3.x 中列表中元素的组合
【发布时间】:2017-04-13 10:54:52
【问题描述】:

我目前正在做一个项目,我需要使用算术运算符(+、-、*、/)找到正确的数字组合,并且我需要在 4 个运算符的列表中创建所有可能的元素组合。
对于列表operators = ['+', '-', '*', '/'],我尝试使用list(itertools.combinations_with_replacement(operators ,3)),但它返回一个列表:

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

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

有什么方法或方法可以获得所有可能的组合吗?
谢谢。

【问题讨论】:

  • 你应该使用product...

标签: python python-3.x combinations


【解决方案1】:

这就是itertools.product 的用途:

from itertools import product

result = list(product(operators,repeat=3))

这个结构:

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

【讨论】:

  • 我试过了,但它什么也没做,所以我停止了这个过程,因为我认为有一些错误导致了无限循环。现在我知道这只需要一些时间。谢谢!
  • @SevO 只需要几微秒,你一定很不耐烦:-)
  • @SevO:这实际上以毫秒为单位运行。当然,如果你增加repeat,那么项目的数量就会呈指数级增长。所以从repeat 12 或更多的那一刻起,确实需要很长时间。
  • 好吧,我一开始在 IDLE 中尝试过,但它停止了,这就是为什么我很困惑 :) 谢谢大家的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
相关资源
最近更新 更多