在itertools.products中命名可迭代的部分 [英] Name parts of iterables in itertools.products

查看:36
本文介绍了在itertools.products中命名可迭代的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关itertools的信息,这似乎是一个非常强大的模块.我对itertools.product()特别感兴趣,它似乎给了我所有可迭代输入的组合.

I've been reading about itertools, which seems to be a very powerful module. I am particularly interested in itertools.product() which appears to give me all of the combinations of the iterable inputs.

但是,我想知道每个输出来自哪个输入可迭代项.例如,一个简单的标准示例是:

However, I would like to know which of the input iterables each of the outputs are coming from. For example, a simple standard example is:

itertools.product([1, 2, 3], [1, 2])

如果用户提供了[1,2,3],[1、2]的输入,我将不知道它们的输入顺序,因此得到的结果

If the user provided the inputs of [1,2,3], [1, 2] I won't know which order they came in, so getting a result of

(1, 2)

并没有太大帮助,因为我不知道它们将如何发展.有什么办法可以提供输入,例如:

isn't much help, as I don't know which way round they will be. Is there some way of providing input like:

itertools.product(foo = [1, 2, 3], bar = [1, 2])

,然后得到如下输出:

output['foo'] = 1
output['bar'] = 2

output.foo = 1
output.bar = 2

推荐答案

itertools.product([1, 2, 3], [1, 2])的输出是一系列有序对,无论第一个元素来自[1,2,3]还是第二个元素来自[1,2].这是有保证的行为.

The output of itertools.product([1, 2, 3], [1, 2]) is a series of ordered pairs whether the first element comes from [1,2,3] and the second element from [1,2]. This is guaranteed behavior.

如果需要字段名称,则可以将结果强制转换为命名为元组.根据您的要求,使用命名的元组可以使用output.foooutput.bar访问字段.结合了KennyTM使用**items的想法,可以将其打包为一个快速且高效存储的功能:

If field names are desired, you can cast the result to a named tuple. As you requested, the named tuple lets you access the fields with output.foo and output.bar. Incorporating KennyTM's idea of using **items, it can be packaged in a single function that is fast and memory efficient:

from itertools import product, starmap
from collections import namedtuple

def named_product(**items):
    Product = namedtuple('Product', items.keys())
    return starmap(Product, product(*items.values()))

这是一个示例调用:

>>> for output in named_product(foo=[1,2,3], bar=[1,2]):
        print output

Product(foo=1, bar=1)
Product(foo=1, bar=2)
Product(foo=2, bar=1)
Product(foo=2, bar=2)
Product(foo=3, bar=1)
Product(foo=3, bar=2)

这篇关于在itertools.products中命名可迭代的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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