【问题标题】:How do I add constraints to Itertools Product?如何向 Itertools 产品添加约束?
【发布时间】:2023-01-07 00:37:09
【问题描述】:

我试图列出 numbers = [1,2,3,4,5,6,7,8] 字符串长度为 4 的所有产品,但有一些限制。

  • 位置 0 必须 < 8
  • 位置 2 和 3 必须 < 6

使用当前代码,它正在打印所有可能的组合,所以我想知道如何过滤它?

import itertools

number = [1,2,3,4,5,6,7,8]

result = itertools.product(number, repeat=4)

for item in result:
    print(item) 

我试过使用if product[0] &lt; 8 or product[2] &lt; 6 or product[3] &lt; 6:,但我不知道该放在哪里或如何格式化它。

【问题讨论】:

  • Position 0 must be &lt; 8Positions 2 and 3 must be &lt; 6 是什么意思?你从哪里得到8和6?
  • 我希望排除 [8 , 8 , 6, 6] / [8, 8, 8 ,7] 等字符串。
  • 在传递给 product 之前进行过滤,以获得等效于:product('1234567', '12345', '12345', '12345678')

标签: python python-itertools


【解决方案1】:

使用 and 而不是 or

for item in result:
    if item[0] < 8 and item[2] < 6 and item[3] < 6:
        print(item)

【讨论】:

    【解决方案2】:

    您必须使用 and 而不是 or 来获取位置 2 和 3 必须 < 6 并且位置 0 必须 < 8。并将此语句放入 for 循环 if item[0] &lt; 8 and item[2] &lt; 6 and item[3] &lt; 6:

    所以你的最终代码应该是:

    import itertools
    
    number = [1,2,3,4,5,6,7,8]
    
    result = itertools.product(number, repeat=4)
    
    for item in result:
        if item[0] < 8 and item[2] < 6 and item[3] < 6:
            print(item)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多