Custom Search

Tuesday, January 8, 2013

python create zero matrix

using for loop
===========
>>>
>>> m = 5
>>> n = 5
>>>
>>>
>>>
>>> res = []
>>> for x in range(m):
...     r = []
...     for y in range(n):
...             r.append(0)
...     res.append(r)

>>>
>>>
>>>
>>> res
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>>
>>>

using listcomprehesion
=================
>>>
>>> [ [0] for x in range(m) for y in range(n) ]
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>>
>>>
>>>
>>> [ [ 0 for x in range(m) ] for y in range(n) ]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>>
>>>
>>>

No comments:

Post a Comment