How to get the length of an itertools.product?

前端 未结 4 969
無奈伤痛
無奈伤痛 2021-02-18 18:14

I am using itertools to run a numerical simulation iterating over all possible combinations of my input parameters. In the example below, I have two parameters and

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-18 18:54

    To implement Kevin's answer for an arbitrary number of source iterables, combining reduce and mul:

    >>> import functools, itertools, operator
    >>> iters = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> functools.reduce(operator.mul, map(len, iters), 1)
    27
    >>> len(list(itertools.product(*iters)))
    27
    

    Note that this will not work if your source iterables are themselves iterators, rather than sequences, for the same reason your initial attempts to get the length of the itertools.product failed. Python generally and itertools specifically can work in a memory-efficient way with iterators of any length (including infinite!) so finding out lengths up-front isn't really a case it was designed to deal with.

提交回复
热议问题