0

I want to define an array which contains all combinations of values

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

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

...

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

Obviously, one could do something like this:

N = 10
array = np.array([[0,0]])
for i in range(N):
    for j in range(N):
        array = np.append(array, [[i,j]], axis=0)
print(array)

However, I find this "ugly". Is there a clean way to generate such an array?

2 Answers 2

2

You can use np.indices, if you prefer:

data=np.indices((512,512)).swapaxes(0,2).swapaxes(0,1)
data.shape
# output: (512, 512, 2)

data[5,0]
# output: array([5, 0])
data[5,25]
#output: array([5, 25])
Sign up to request clarification or add additional context in comments.

1 Comment

You can use np.transpose(data, (1, 2, 0)). I find it more readable than chaining swapaxes.
1

Here are a few ideas you can probably use as well.

Using combinations from itertools:

from itertools import combinations
someList = [i for i in combinations(range(N), 2)]

Using product is a nice way to reduce nested for loops and condense down into list comprehensions:

someList = [[i,j] for i,j in product(range(N), range(N))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.