【问题标题】:generating tuples using n-lists with itertools.product使用带有 itertools.product 的 n 列表生成元组
【发布时间】:2013-11-02 15:43:51
【问题描述】:

如果我不知道列表的数量,如何使用itertools.product 函数?我有列表,里面有列表。

喜欢,

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

通常我需要这样做,

product([1,2,3],[6,7,8],[2,4,5])

如果输入是示例中的列表,我该怎么做?

【问题讨论】:

    标签: python python-2.7 itertools cartesian-product


    【解决方案1】:

    尝试以下操作:
    product(*lis)
    它被称为argument unpacking
    简短说明:您也可以将参数解包与命名参数一起使用,带有双星:

    def simpleSum(a=1,b=2):
        return a + b
    simpleSum(**{'a':1,'b':2}) # returns 3
    

    【讨论】:

    • 我不知道。我一定会检查的。还是谢谢。
    • @genclik27 不客气。您也可以将其与命名参数一起使用,请查看我更新的答案。
    【解决方案2】:

    使用argument unpacking:

    >>> lis = [[1,2,3],[6,7,8],[2,4,5]]
    >>> list(itertools.product(*lis))
    [(1, 6, 2), (1, 6, 4), (1, 6, 5), (1, 7, 2), (1, 7, 4), (1, 7, 5), (1, 8, 2),
     (1, 8, 4), (1, 8, 5), (2, 6, 2), (2, 6, 4), (2, 6, 5), (2, 7, 2), (2, 7, 4),
     (2, 7, 5), (2, 8, 2), (2, 8, 4), (2, 8, 5), (3, 6, 2), (3, 6, 4), (3, 6, 5),
     (3, 7, 2), (3, 7, 4), (3, 7, 5), (3, 8, 2), (3, 8, 4), (3, 8, 5)]
    >>>
    

    【讨论】:

    • 非常简单。谢谢,这就是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2020-03-12
    相关资源
    最近更新 更多