Bartek Nowakowski
Bartek Nowakowski

Reputation: 271

Python - create matrix of tuples

I need to create a 9x9 matrix of tuples. I already have a code:

squares, sub = [], []
for y in [3, 6, 9]:
    sub.append([[(y, x) for x in range(1, 10) if x % 3 == 0] for x in range(1, 10) if x % 3 == 0])

for i in sub:
    sq = []
    for j in i:
        sq.extend(j)
    sq.sort()
    squares.append(sq)
    squares.append(sq)
    squares.append(sq)

with such result:

[[(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)]]

Result is exactly as I want it to be, but do you think there is a better way to write it? Can it be done simpler?

Edit:

Result should be always identical, there isn't any dynamic input and it won't be edited afterwards. Just a static matrix used in a different part of my code.

Upvotes: 1

Views: 481

Answers (1)

CristiFati
CristiFati

Reputation: 41147

The question is a bit unclear, as the final list (and the code) might be interpreted, and there might be multiple interpretations with the same result.

For one such interpretation, you could use a (twisted and kind of funny looking) nested list comprehension ([Python 3.Docs]: Data Structures - List Comprehensions):

>>> from pprint import pprint as pp  # For print purposes only
>>>
>>> l = [3, 6, 9]
>>>
>>> items = [[i0 for i1 in l for i0 in ((i2, i1),) * len(l)] for i2 in l for _ in l]
>>>
>>> pp(items)
[[(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)]]

Note: Attempting to modify your final list (squares[0][0] = 1) might yield "unexpected" results.

Upvotes: 2

Related Questions