英文:
Most efficient way to create an (n*m by m) numpy array with the first row all zeros and last row all n in Python?
问题
以下是翻译好的内容,去除了代码部分:
我正在寻找创建一个具有m列的数组的最有效方法,以便最终结果如下:
如果n = 2,m = 3,我们将得到:
我尽量避免使用for循环,并希望能够将其扩展,以便可以给出任何正整数(n,m)。
额外问题:是否有一个这样的数组的名称?
我尝试过np.meshgrid(),但那不会产生正确的数组。我尝试过np.repeat(),也失败了。
英文:
I am looking for the most effective way to create an array that has m columns so that the final outcome is:
[[0, 0, 0, ..., 0]
[1, 0, 0, ..., 0]
[2, 0, 0, ..., 0]
[3, 0, 0, ..., 0]
[4, 0, 0, ..., 0]
[5, 0, 0, ..., 0]
...
[n, 0, 0, ..., 0]
[n, 1, 0, ..., 0]
[n, 2, 0, ..., 0]
...
[n, n, 0, ..., 0]
...
[n, n, n, ..., n-3]
[n, n, n, ..., n-2]
[n, n, n, ..., n-1]
[n, n, n, ..., n]]
If n = 2 and m = 3 we would have:
[[0, 0, 0]
[1, 0, 0]
[2, 0, 0]
[0, 1, 0]
[1, 1, 0]
[2, 1, 0]
[0, 2, 0]
[1, 2, 0]
[2, 2, 0]
[0, 0, 1]
[1, 0, 1]
[2, 0, 1]
[0, 1, 1]
[1, 1, 1]
[2, 1, 1]
[0, 2, 1]
[1, 2, 1]
[2, 2, 1]
[0, 0, 2]
[1, 0, 2]
[2, 0, 2]
[0, 1, 2]
[1, 1, 2]
[2, 1, 2]
[0, 2, 2]
[1, 2, 2]
[2, 2, 2]]
I am trying to avoid as much as possible for-loops, and I would like to be able to scale it up so that I can give any positive, non-null (n,m).
Bonus question: is there a name for such an array?
I have tried np.meshgrid(), but that does not yield to the right array.
I tried np.repeat(), and also failed.
答案1
得分: 1
你可以使用 itertools 的 product
函数,然后执行以下代码:
n = 2
m = 3
# 注意:我使用 perm[::-1] 来颠倒 product 输出的顺序,以匹配问题中所需的顺序
output = np.array(
[perm[::-1] for perm in product(range(n + 1), repeat=m)]
)
print(output)
[[0 0 0]
[1 0 0]
[2 0 0]
[0 1 0]
[1 1 0]
[2 1 0]
[0 2 0]
[1 2 0]
[2 2 0]
[0 0 1]
[1 0 1]
[2 0 1]
[0 1 1]
[1 1 1]
[2 1 1]
[0 2 1]
[1 2 1]
[2 2 1]
[0 0 2]
[1 0 2]
[2 0 2]
[0 1 2]
[1 1 2]
[2 1 2]
[0 2 2]
[1 2 2]
[2 2 2]]
英文:
You can use the itertools product
function and do:
n = 2
m = 3
# note: I do perm[::-1] to reverse the output of
# product to match the required order in the question
output = np.array(
[perm[::-1] for perm in product(range(n + 1), repeat=m)]
)
print(output)
[[0 0 0]
[1 0 0]
[2 0 0]
[0 1 0]
[1 1 0]
[2 1 0]
[0 2 0]
[1 2 0]
[2 2 0]
[0 0 1]
[1 0 1]
[2 0 1]
[0 1 1]
[1 1 1]
[2 1 1]
[0 2 1]
[1 2 1]
[2 2 1]
[0 0 2]
[1 0 2]
[2 0 2]
[0 1 2]
[1 1 2]
[2 1 2]
[0 2 2]
[1 2 2]
[2 2 2]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论