简体   繁体   English

Python:循环可变数量的输入

[英]Python: Looping over a variable number of inputs

Is there a way to efficiently feed in a variable number of inputs into a program like itertools.product() when the number of iterables varies based on user input?当可迭代的数量根据用户输入而变化时,有没有办法有效地将可变数量的输入输入到像 itertools.product() 这样的程序中?

For example, the code below runs, but needs to be explicitly defined for each loop:例如,下面的代码运行,但需要为每个循环显式定义:

steps = np.linspace(0,100,21)

if len(elem_list) == 2:
    for phase in itertools.product(steps,steps):
        if round(round(phase[0],10)+round(phase[1],10),10)==100:
            print(phase)

if len(elem_list) == 3:
    for phase in itertools.product(steps,steps,steps):
        if round(round(phase[0],10)+round(phase[1],10)+round(phase[2],10),10)==100:
            print(phase)
            
if len(elem_list) == 4:
    for phase in itertools.product(steps,steps,steps,steps):
        if round(round(phase[0],10)+round(phase[1],10)+round(phase[2],10)+round(phase[3],10),10)==100:
            print(phase)
            
if len(elem_list) == 5:
    for phase in itertools.product(steps,steps,steps,steps,steps):
        if round(round(phase[0],10)+round(phase[1],10)+round(phase[2],10)+round(phase[3],10)+round(phase[4],10),10)==100:
            print(phase)

where elem_list contains a variable number of elements input by the user.其中 elem_list 包含用户输入的可变数量的元素。

Is there any way to write this more concisely and so it can be generally applied to any length of elem_list?有什么方法可以更简洁地编写它,因此它通常可以应用于任何长度的 elem_list? Thanks!谢谢!

itertools.product accepts a repeat argument exactly for this. itertools.product完全为此接受repeat参数。 Use it along with sum and map .将它与summap一起使用。

I'm not sure why you need round (or round(..., 10) for that matter) since steps includes whole numbers (so summing them is guaranteed to give a whole number) but this is the way to go.我不确定为什么你需要round (或round(..., 10) ),因为steps包括整数(所以对它们求和肯定会给出一个整数),但这是要走的路。

steps = np.linspace(0, 100, 21)

for phase in itertools.product(steps, repeat=len(elem_list)):
    if sum(map(round, phase)) == 100:
        print(phase)

As @DeepSpace mentions, repeat= is the perfect way to handle when all the iterated items are the same.正如@DeepSpace 提到的,当所有迭代项都相同时,repeat= 是处理的完美方式。 And that sounds like what you wants.这听起来像你想要的。

In more complicated cases, you can use a list of ranges.在更复杂的情况下,您可以使用范围列表。 And this list can be arbitrarily generated.并且这个列表可以任意生成。

list_of_ranges = [range(5), (1, 3, 7), range(10), (True, False)]
itertools.product(*list_of_ranges)

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

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