0

I'm looking to fill a 3x3 matrix in the most pythonic way from a 1D list.

So transform from the first to the second

[1,2,3,4,5,6,7,8,9]

[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

so far I can fill the first as such:

l = [1,2,3,4,5,6,7,8,9]
m = [[l[y] for y in range(3)] for x in range(3)]

but this gives

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
wprins
  • 846
  • 2
  • 19
  • 35

2 Answers2

0

You can do something like this using list comprehension:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [a[k:k+3] for k in range(0,len(a),3)]

Output:

print(b)
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can also, create a method for this case to handle the resizing of your array:

def reshape(a = list, r = 1):
    return [a[k:k+r] for k in range(0,len(a),r)]

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

print(reshape(a, 3))
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(reshape(a,2))
>>> [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
0

Given:

l = [1,2,3,4,5,6,7,8,9]

You can create N iterators and then zip them together. This technique is described in the itertools Recipes section of the docs, under grouper.

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

print(list(grouper(l, 3)))

Output:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
aghast
  • 14,785
  • 3
  • 24
  • 56