【问题标题】:itertools product function two elements at a time in a list [closed]itertools产品功能列表中的两个元素[关闭]
【发布时间】:2020-12-13 09:46:43
【问题描述】:

我有以下清单:

L = [0, 25, 50, 75, 100]

我想查找此列表的所有可能组合,但一次查找两个元素,例如:

Combi = [(0, 0), (0, 25), (25,0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75)...]

等等。

有没有简洁的方法来实现这一点?

【问题讨论】:

  • documentation 对此进行了介绍。使用参数repeat=2
  • list(combinations_with_replacement(L, 2))?
  • @Prune 给了我(0, 0), (0, 25), (0, 50)... 等组合。我想要我提到的每对重复组合的结果。
  • @deadshot 也没有给我每对的重复组合。还有什么我可以尝试的吗?
  • list(combinations_with_replacement(L, 2)) + list(combinations_with_replacement(L[::-1], 2))?

标签: python python-3.x combinations itertools cartesian-product


【解决方案1】:

似乎您想要输入中所有唯一对的乘积。您可以将三个itertools 函数捆绑在一起来实现:

from itertools import chain, combinations, product

L = [0, 25, 50, 75, 100]

print(list(chain.from_iterable(product(pair, repeat=2) for pair in combinations(L, 2))))

输出符合您的规格:

[(0, 0), (0, 25), (25, 0), (25, 25), (0, 0), (0, 50), (50, 0), (50, 50), (0, 0), (0, 75), (75, 0), (75, 75), (0, 0), (0, 100), (100, 0), (100, 100), (25, 25), (25, 50), (50, 25), (50, 50), (25, 25), (25, 75), (75, 25), (75, 75), (25, 25), (25, 100), (100, 25), (100, 100), (50, 50), (50, 75), (75, 50), (75, 75), (50, 50), (50, 100), (100, 50), (100, 100), (75, 75), (75, 100), (100, 75), (100, 100)]

如果您想将所有工作推送到 C 层(每个组合不执行生成器表达式字节代码),另一个导入(以及一些更密集的代码)可以让您到达那里:

from functools import partial

print(list(chain.from_iterable(map(partial(product, repeat=2), combinations(L, 2)))))

【讨论】:

    【解决方案2】:

    试试

    out=[]
    for c in list(it.combinations(L,2)):
      out.extend (it.product(c, repeat=2))
    

    【讨论】:

    • 你(几乎)永远不需要在 list 构造函数中包装你正在迭代的东西(罕见的例外是当你改变你正在迭代的东西时,不是这种情况这里)。 for c in it.combinations(L, 2): 将完成这项工作,而不会浪费地制作一个临时的 list
    • 是的,谢谢
    【解决方案3】:

    使用列表理解的某种方法:

    list = [0, 25, 50, 75, 100]
    new_list = [(list[i], j) for i in range(len(list)) for j in list]
    

    【讨论】:

      【解决方案4】:

      如果我理解正确的话,给你:

      from itertools import combinations_with_replacement
      
      L = [0, 25, 50, 75, 100]
      
      combi = []
      for a,b in combinations_with_replacement(L, 2):
          combi.append((a,b))
          if a != b:
              combi.append((b,a))
      

      给予:

      [(0, 0),
       (0, 25),
       (25, 0),
       (0, 50),
       (50, 0),
       (0, 75),
       (75, 0),
       (0, 100),
       (100, 0),
       (25, 25),
       (25, 50),
       (50, 25),
       (25, 75),
       (75, 25),
       (25, 100),
       (100, 25),
       (50, 50),
       (50, 75),
       (75, 50),
       (50, 100),
       (100, 50),
       (75, 75),
       (75, 100),
       (100, 75),
       (100, 100)]
      

      【讨论】:

        猜你喜欢
        • 2020-05-05
        • 2016-11-29
        • 1970-01-01
        • 2010-10-17
        • 1970-01-01
        • 2016-06-08
        • 2019-03-31
        • 1970-01-01
        • 2017-06-28
        相关资源
        最近更新 更多