我试图使用一些修复参数来进行可迭代,并且迭代参数在列表中。这是我要找的东西的输出:
(fix1, fix2, fix3, [iterable1_1, iterable2_1, iterable3_1], fix4)
(fix1, fix2, fix3, [iterable1_1, iterable2_1, iterable3_2], fix4)基本上,只有列表中的三个变化,其余的不会改变。
到目前为止,我已经试过这个了,但实际上不起作用。
iterable = itertools.product([fix1], [fix2], [fix3], [[iter1_1, iter1_2, iter1_3], [iter2_1, iter2_2], [iter3_1, iter3_2, iter3_3]], [fix4])iter1、iter2和iter3有不同的长度,但我认为这与此无关。
例如:我有两个列表,a= 1,2和b= 3,4和一些修复参数f1 = 10,f2=20,f3=30,所需的输出是:
(10, 20, [1,3], 30)
(10, 20, [1,4], 30)
(10, 20, [2,3], 30)
(10, 20, [2,4], 30)发布于 2017-04-03 19:05:30
听起来你想要的是:
result = [(fix1, fix2, fix3, [a, b, c], fix4)
for a, b, c in itertools.product(iterable1, iterable2, iterable3)]如果a, b, c的内部序列可以是元组而不是列表,则不需要解压缩:
result = [(fix1, fix2, fix3, prod, fix4) for prod in product(...)]发布于 2017-04-03 19:07:21
import itertools
a = [1,2]
b = [3,4]
f1 = 10
f2 = 20
f3 = 30得到a和b的乘积
things = itertools.product(a,b)用固定值和乘积构造结果
z = [(f1, f2, thing, f3) for thing in map(list, things)]
>>> for thing in z:
print thing
(10, 20, [1, 3], 30)
(10, 20, [1, 4], 30)
(10, 20, [2, 3], 30)
(10, 20, [2, 4], 30)
>>>它不是泛型的,它不会处理任意数量的固定和可迭代的事物。
下面是一个更通用的解决方案
def f(fixed, iterables):
things = itertools.product(*iterables)
last = fixed[-1]
for thing in things:
out = fixed[:-1]
out.extend((thing, last))
yield out用法:
for thing in f([f1, f2, f3, f4], [a, b]):
print thing发布于 2017-04-03 19:05:11
如果有疑问,创建一个函数。
def framed(*iters):
for pair in itertools.product(*iters):
yield (10, 20, pair, 30)
for result in framed([1, 2], [3, 4]):
print result
(10, 20, (1, 3), 30)
(10, 20, (1, 4), 30)
(10, 20, (2, 3), 30)
(10, 20, (2, 4), 30)https://stackoverflow.com/questions/43191937
复制相似问题