【问题标题】:Python itertools.product with arbitrary number of setsPython itertools.product 具有任意数量的集合
【发布时间】:2013-08-20 17:52:34
【问题描述】:

我希望执行以下代码:

temp = []
temp.append([1,2])
temp.append([3,4])
temp.append([5,6])

print list(itertools.product(temp[0],temp[1],temp[2]))

但是,我想对任意长度的 temp 执行它。 IE。更像是:

print list(itertools.product(temp))

如何在不明确知道 temp 中有多少条目的情况下为 itertools.product 正确格式化输入以在第一段代码中产生相同的结果?

【问题讨论】:

    标签: python product itertools


    【解决方案1】:
    print list(itertools.product(*temp))
    

    使用* 将可迭代的参数解包为单独的位置参数。

    【讨论】:

    • 抱歉,经过一番搜索后找到了解决方案。而且现在不能删除。对不起!
    • @user2331057 无需删除 - 发布您找到的解决方案作为答案是正确的做法。如果它令人满意地解决了您的问题,现在接受您自己的答案。
    • @Brionius:我不是 OP。我们的用户名看起来非常相似,但您可以看到我们的代表人数不同,他的名字有蓝色背景。
    • @user2357112 啊,我的错!
    【解决方案2】:

    或者可以这样做:

    使用 zip 组合列表。 结果是一个列表迭代器。

    a = ["A", "a"]
    b = ["B", "b"]
    c = ["C", "c"]
    
    number_iterator = zip(a,b,c)
    numbers = list(number_iterator)
    
    print (numbers)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 2023-03-10
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多