Python itertools产品,但有条件吗? [英] Python itertools product, but conditional?
问题描述
我有一个有趣的函数,它带有几个参数p0,p1,..对于每个参数,我给出一个可能值的列表:
I have a function fun that takes several parameters p0,p1,.. For each parameter i give a list of possible values:
p0_list = ['a','b','c']
p1_list = [5,100]
我现在可以为p0,p1的每个组合调用我的函数
I can now call my function for every combination of p0,p1
for i in itertools.product(*[p0,p1]):
print fun(i)
现在出现了问题:如果我已经知道,如果p0是'a'或'c',那么参数p1仅对fun的结果有影响呢?在这种情况下,我需要我的参数组合列表如下所示:
Now comes the problem: What if i already know, that the parameter p1 only has an effect on the result of fun, if p0 is 'a' or 'c'? In this case i need my list of parameter combinations to look like:
[('a', 5), ('a',100), ('b', 5), ('c',5), ('c', 100)]
因此('b',100)被省略了,因为这是对乐趣的不必要的评估.
So ('b', 100) is just omitted, as it would be an unecessary evaluation of fun.
我的最终解决方案:
param_lists = [['p0', ['a','b','c']],['p1', [5,100]]]
l = itertools.product(*[x[1] for x in param_lists])
l = [x for x in l if not x[0] == 'b' or x[1]==5]
我将这种方法用于5个参数和各种条件,并且效果很好.也很容易阅读.该代码的灵感来自Corley Brigmans和nmcleans的答案.
I used this approach for 5 parameters and various conditions and it works fine. It's pretty easy to read as well. This code is inspired by Corley Brigmans' and nmcleans' answers.
推荐答案
您可以生成它,然后隐藏重复项".但是单独生成可能更好:
You could generate it, and then suppress 'duplicates'. But probably just better to generate separately:
p0_list = ['a', 'b', 'c']
p0_noarg1 = ['b']
sp0_noarg1 = set(p0_noarg1)
p0_arg1 = [x for x in p0_list if x not in sp0_noarg1]
p1_list = [5, 100]
total_list = [x for x in itertools.product(p0_arg1, p1_list)] + [x for x in itertools.product(p0_noarg1, p1_list[:1])]
这篇关于Python itertools产品,但有条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!