【问题标题】:Python Itertools on two lists. Get more then 1 value from each listPython Itertools 在两个列表中。从每个列表中获取超过 1 个值
【发布时间】:2020-03-30 09:50:13
【问题描述】:

我有下面的代码。这段代码给出了 list1 和 list2 之间所有可能的组合。

import itertools
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
print(list(itertools.product(list1, list2)))

Output:
[(1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10)]

我想要的是从 list1 中获取 2 个值的所有可能组合,从 list2 中获取 3 个值(不重复)。所以可能的输出应该如下。我该怎么做?

[(1,2,6,7,8), (1,2,7,8,9), (1,2,8,9,10), (2,3,6,7,8), and so on.......]

【问题讨论】:

    标签: python list permutation itertools


    【解决方案1】:

    以下会做:

    from itertools import combinations as com, product as prod
    
    list1 = [1, 2, 3, 4, 5]
    list2 = [6, 7, 8, 9, 10]
    
    [c1 + c2 for c1, c2 in prod(com(list1, 2), com(list2, 3))]
    
    # [(1, 2, 6, 7, 8), 
    #  (1, 2, 6, 7, 9), 
    #  (1, 2, 6, 7, 10),
    #  ...
    #  (4, 5, 7, 9, 10), 
    #  (4, 5, 8, 9, 10)]
    

    这会生成两个列表中各自组合的笛卡尔积,并简单地连接每一对以避免嵌套元组。

    【讨论】:

    • 回答您的问题。笛卡尔积是否有重复项?
    • 好吧,在集合论中,没有。然而,在 Python 中,如果其中一个池(可以是任何可迭代对象)中有重复项,则产品中也会有重复项。
    【解决方案2】:

    你需要先为每个列表建立你需要的组合,然后做产品,你还需要加入产品((1, 2), (6, 7, 8)) => (1, 2, 6, 7, 8)的内部结果

    list1 = [1, 2, 3, 4, 5]
    list2 = [6, 7, 8, 9, 10]
    
    c1 = combinations(list1, r=2)
    c2 = combinations(list2, r=3)
    
    print(list(map(lambda x: tuple(chain(*x)), product(c1, c2)))) # [(1, 2, 6, 7, 8), (1, 2, 6, 7, 9), (1, 2, 6, 7, 10), (1, 2, 6, 8, 9), (1, 2, 6, 8, 10), (1, 2, 6, 9, 10), (1, 2, 7
    

    【讨论】:

      猜你喜欢
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2022-10-03
      相关资源
      最近更新 更多