0

I have the following list of tuples:

>>> import itertools
>>> import numpy as np
>>> grid = list(itertools.product((1,2,3),repeat=2))
>>> grid
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

I'd like to reshape this list in a sensible way (e.g. using numpy if possible) to be 3x3 as follows:

[[(1, 1), (1, 2), (1, 3)],
 [(2, 1), (2, 2), (2, 3)],
 [(3, 1), (3, 2), (3, 3)]]

When I do np.reshape(grid, (3, 3)) I get the following error: ValueError: cannot reshape array of size 18 into shape (3,3) (size 18??)

I've tried variations of np.reshape(grid, (3, 3, 2)) but these don't return the 3x3 grid given above.

1
  • While it is possible to make a (3,3) array of tuples, is that really what you need? What's wrong with the (3,3,2) array of numbers? Do you understand the difference? Commented Mar 25, 2022 at 0:33

2 Answers 2

1

This will do the job:

new_grid = np.empty(len(grid), dtype='object')
new_grid[:] = grid
new_grid = new_grid.reshape(3, 3)

This outputs:

array([[(1, 1), (1, 2), (1, 3)],
       [(2, 1), (2, 2), (2, 3)],
       [(3, 1), (3, 2), (3, 3)]], dtype=object)

The object type will remain tuple:

type(new_grid[0, 0])
tuple
Sign up to request clarification or add additional context in comments.

Comments

1

18 comes from the fact that you have a list of 9 tuples, each containing 2 items; thus, 9 * 2 = 18. numpy automatically converts the tuples to part of the array.

You can either use LeonardoVaz's answer or do it speedily with nested list comprehension:

reshaped_grid = [[grid[i+j] for j in range(3)] for i in range(0, len(grid), 3)]

Output:

>>> reshaped_grid
[
    [(1, 1), (1, 2), (1, 3)],
    [(2, 1), (2, 2), (2, 3)],
    [(3, 1), (3, 2), (3, 3)]
]

2 Comments

The output grid here is not what the question asks for.
@K-- Oops! Corrected :)

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.