如何获得itertools.product的长度? [英] How to get the length of an itertools.product?

查看:112
本文介绍了如何获得itertools.product的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用itertools来运行数值模拟,以对输入参数的所有可能组合进行迭代.在下面的示例中,我有两个参数和六个可能的组合:

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 six possible combinations:

import itertools

x = [0, 1]
y = [100, 200, 300]

myprod = itertools.product(x, y)

for p in myprod:
    print p[0], p[1]
    # run myfunction using p[0] as the value of x and p[1] as the value of y

如何获取myprod的大小(在示例中为六个)?我需要在for循环开始之前将其打印出来.

How can I get the size of myprod (six, in the example)? I'd need to print this before the for loop starts.

我了解myprod不是列表.我可以计算len(list(myprod)),但这会消耗迭代器,因此for循环将不再起作用.

I understand myprod is not a list. I can calculate len(list(myprod)), but this consumes the iterator so the for loop no longer works.

我尝试过:

myprod2=copy.deepcopy(myprod)
mylength = len(list(myprod2))

但是这也不起作用.我可以做到:

but this doesn't work, either. I could do:

myprod2=itertools.product(x,y)
mylength = len(list(myprod2))

但是它几乎没有优雅和Python风格!

but it's hardly elegant and pythonic!

推荐答案

为任意数量的内容实施 Kevin的答案源Iterable,将 reduce

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

请注意,如果您的源可迭代对象本身是迭代器,而不是序列,则这将不起作用,出于相同的原因,您最初尝试获取itertools.product的长度的尝试也会失败.通常,Python尤其是itertools可以与任意长度的迭代器(包括无限!)一起以内存有效的方式工作,因此预先确定长度并不是设计它要处理的情况.

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.

这篇关于如何获得itertools.product的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆