Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成未知数量变量的所有组合_Python_Loops_Dynamic_Combinations - Fatal编程技术网

Python 生成未知数量变量的所有组合

Python 生成未知数量变量的所有组合,python,loops,dynamic,combinations,Python,Loops,Dynamic,Combinations,我有一个变量列表,变量的数量可以改变。每个变量都有一个下限、上限和一个增量值。例如: variables = { "a": [1, 10, 1], "b": [50, 200, 5], "c": [50, 300, 10] } 其中,对于键“a”,1为下限,10为上限,1为增量 "a" would go from 1 through 10, incrementing by 1 "b" would go from 50 through 200, incrementing by

我有一个变量列表,变量的数量可以改变。每个变量都有一个下限、上限和一个增量值。例如:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
其中,对于键“a”,1为下限,10为上限,1为增量

"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.
我需要创建一个包含所有可能的a、b和c组合的列表,而不需要硬编码嵌套循环,因为变量/键的数量未知,我无法理解。我正在使用Python 3.7

理想情况下,输出是每个变量的组合表,可能是逗号分隔的值。比如说

a  b  c
x  y  z
x  y  z
x  y  z
x  y  z
但是,只要我能够将输出整理成一种格式,在这种格式中,每个组合都可以作为一个集合访问,任何事情都可以。例如元组列表

[
  (x, y, z)
  (x, y, z)
]
...
尝试:

试着这样做:

var=[]
for k in variables.keys():
  var.append(np.arange(variables[k][0],variables[k][1]+1,variables[k][2]))

np.array(np.meshgrid(var[0],var[1],var[2])).T.reshape(-1,3)

对于组合,我从

获得了帮助,您可以使用:

输出:

在此,假设:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
然后可以使用
itertools
创建迭代器:

from itertools import product, starmap
cartesian_product = product(*starmap(range, variables.values()))
或者,只是为了告诉你星图在做什么:

cartesian_product = product(*(range(*v) for v in variables.values()))

您能发布一个输出示例吗听起来像是您可以使用的(显然是在创建变量数组之后),我认为您可以研究python itertools模块。这似乎需要已知数量的变量。您可以使用for loop for
np.arange
谢谢。这似乎需要已知数量的变量。当这个代码可能回答这个问题时,你能考虑为你解决的问题增加一些解释,以及你是如何解决的?这将帮助未来的读者更好地理解你的答案,并从中学习。@SidKhullar如果这有帮助,will by nice如果你接受我的答案:)这很有效,很好,谢谢,但我如何使这部分充满活力<代码>结果=itertools.product(a、b、c);特别是“a,b,c”?@SidKhullar by
dynamic
你的意思是设置不同的变量数或不同数量的数组?为什么在这里设置
numpy
?只需使用
range
@juanpa.arrivillaga,你能分享我可以尝试的代码片段吗?非常感谢!这里还有一个问题。dict源代码定义中键的顺序是否总是反映在元组元素的顺序中?或者您建议我使用OrderedDict吗?@SidKhullar如果您使用的是python版本>=3.7,那么是的,它保持插入顺序。否则,它不会。我的一些值是浮点数,这会导致TypeError。你能提出一个解决方案吗?
variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
from itertools import product, starmap
cartesian_product = product(*starmap(range, variables.values()))
cartesian_product = product(*(range(*v) for v in variables.values()))