【问题标题】:Crate a List of elements from different combination of list iltems从列表项的不同组合中创建元素列表
【发布时间】:2020-11-25 12:08:24
【问题描述】:

我有N number of List。在这里,我举两个例子。

List_1 = [5,6,7,8,9,10]
List_2 = [5,6,7,8,9,10]

我想从这 N 个列表中创建一个List of tuple。对于列表输出的两个元素应该是,

 [(5,),(6,),(7,),(8,),(9,),(10,),(5,5,),(5,6)....(5,10),(6,5,),(6,6)....(6,10),(7,5,),(7,6)....(7,10)
.............(10,10)]

输出元素是1 to N number of elements pair using all combinations of list elements

List_1 = [5,6,7,8,9,10]
List_2 = [5,6,7,8,9,10]
List_3 = [5,6,7,8,9,10]

对于 3 个列表元素的输出是,

 [(5,),(6,),(7,),(8,),(9,),(10,),(5,5,),(5,6)....(5,10),(6,5,),(6,6)....(6,10),(7,5,),(7,6)....(7,10)
.............(10,10),(5,5,5)..(all combination of 1 ,2 & 3 elements items of three list)...(10,10,10)] 

注意:所有列表都具有相同的值

【问题讨论】:

    标签: python python-3.x list list-comprehension itertools


    【解决方案1】:

    这可能是一个可能的解决方案:

    from itertools import product
    
    #since the lists have the same value, we need to save it once and decide how many times repeat the product
    List_1 = [5,6,7,8,9,10]
    list_repetition = 2
    
    result = []
    for i in range(list_repetition):
        result.extend(tuple(product(List_1, repeat=i+1)))
        
    print(result)
    

    输出将是:

    [(5,), (6,), (7,), (8,), (9,), (10,), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (7, 10), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (8, 10), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9), (9, 10), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 10)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      相关资源
      最近更新 更多