Python:生成范围内值的所有n长度数组组合

标签 python arrays python-3.x list-comprehension

好的。我正在寻找最智能、更紧凑的方式来执行此功能

def f():
    [[a,b,c] for a in range(6) for b in range(6) for c in range(6)]

它应该像这样生成值 a、b、c 的所有组合:

[0,0,0]
[0,0,1]
[0,0,2]
...
[1,0,0]
[1,0,1]
...

等等……

但我希望它是灵活的,这样我就可以更改范围或可迭代对象,以及生成的数组的长度。范围是一件容易的事:

def f(min, max):
    [[a,b,c] for a in range(min,max) for b in range(min,max) for c in range(min,max)]

这对于 3 长度数组没问题,但我现在正在考虑制作 4 长度数组或 7 长度数组,并在同一范围内为它们生成所有组合。

它必须存在一种简单的方法,也许以某种方式连接数组或嵌套理解列表,但我的解决方案似乎太复杂了。

抱歉发了这么长的帖子。

最佳答案

您可以使用 itertools.product这只是嵌套迭代的一个便利函数。如果您想多次重复相同的 iterable,它还有一个 repeat 参数:

>>> from itertools import product

>>> amin = 0
>>> amax = 2
>>> list(product(range(amin, amax), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0),  (0, 1, 1),  (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

要获取 listlist,您可以使用 map:

>>> list(map(list, product(range(amin, amax), repeat=3)))
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

但是 product 是一个迭代器,因此如果您只是对其进行迭代而不是将其强制转换为 list,它会非常高效。至少如果这在你的程序中是可能的。例如:

>>> for prod in product(range(amin, amax), repeat=3):
...     print(prod)  # one example
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

关于Python:生成范围内值的所有n长度数组组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42364851/

相关文章:

python - Django 标签和翻译 - 模型设计

python - 将超链接添加到由 pandas dataframe to_excel 方法创建的 excel 表

python - IndentationError 是否是 Python 中的语法错误?

java - 如何简化井字游戏获胜者检查

C - 如何将数组结构指向变量?

私有(private)类的 Python 名称修饰(带双下划线)

python - 如何在没有服务器的情况下在本地计算机上使用 Mkdocs?

python - os.path.exists 在 python 中没有按预期工作

python - 端口扫描程序上的Python语法问题

javascript - 在 Javascript 中执行(整数)操作的最有效方法是什么?