简体   繁体   English

Python:使用for循环创建未知数量的变量

[英]Python: Creating unknown number of variables using for-loop

I want to create a generator that takes in any number of keyword arguments and it will return the product of the values (give as tuples as shown below). 我想创建一个生成器,该生成器接受任意数量的关键字参数,它将返回值的乘积(给出为元组,如下所示)。

I am having trouble avoiding hardcoding the for loop variables ( hardcoded_a , hardcoded_b ). 我无法避免对for循环变量( hardcoded_ahardcoded_b )进行hardcoded_a hardcoded_b In this scenario if I use more or less than two arguments it gives a ValueError . 在这种情况下,如果我使用的参数多于或少于两个,则会给出ValueError I don't care about hardcoding the 'okay' variables. 我不在乎对“好”变量进行硬编码。 How can I go about it so no matter how many items I pass to kwargs, I can still yield the product? 我该怎么做,所以无论我传递给kwargs多少物品,我仍然可以生产该产品?

This is what I have written so far: 到目前为止,这是我写的:

from itertools import product
def gen(**kwargs):
    options = {}
    [options.update({k: v}) for k, v in kwargs.iteritems()]
    for hardcoded_a, hardcoded_b in product(*(tuple(options.values()))):
       yield hardcoded_a, hardcoded_b

for okay_var1, okay_var2 in gen(dollar=(2, 20), hungry=(True, False)):
    print okay_var1, okay_var2

I think what you're looking for is the following: 我认为您正在寻找以下内容:

def gen(**kwargs):
    options = {}
    [options.update({k: v}) for k, v in kwargs.iteritems()]
    for prod in product(*(tuple(options.values()))):
       yield dict(zip(options, prod))

or an even cleaner solution: 或更干净的解决方案:

def gen(**kwargs):
    for prod in product(*kwargs.values()):
       yield dict(zip(kwargs, prod))

Unless I misunderstand your objective, the following should work: 除非我误解了您的目标,否则以下方法将起作用:

from itertools import product

def gen(**kwargs):
    return product(*kwargs.values())

Example: 例:

>>> print(list(gen(dollar=(2,20), hungry=(True,False))))
[(True, 2), (True, 20), (False, 2), (False, 20)]

It's worth noting, however, that kwargs.values() is not guaranteed to have a specific order. 但是,值得注意的是,不能保证kwargs.values()具有特定的顺序。 This will make sure they are ordered by the "natural ordering" (string comparison) of the keywords: 这将确保它们按关键字的“自然排序”(字符串比较)进行排序:

def gen2(**kwargs):
    return product(*map(lambda t:t[1],sorted(k.items())))

So now: 所以现在:

>>> print(list(gen2(dollar=(2,20), hungry=(True,False))))
[(2, True), (2, False), (20, True), (20, False)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM