Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array of objects in Python

I'm converting some java code to python code and I ended up getting stumped on how to convert a 2D array of objects in Java to python.

Java code:

private Node nodes[][] = new Node[rows][columns];

How would I do this in python?

like image 494
nobody Avatar asked Jun 25 '11 20:06

nobody


1 Answers

I think that's what you want

nodes = [[Node() for j in range(cols)] for i in range(rows)]

But it is not always a good practice to initialize lists. For matrices it may make sense.

If you're wondering: Documentation about list comprehensions

Demo code:

>>> class Node:
      def __repr__(self):
        return "Node: %s" % id(self)
>>> cols = 3
>>> rows = 4
>>> nodes = [[Node() for j in range(cols)] for i in range(rows)]
>>> from pprint import pprint
>>> pprint(nodes)
[[Node: 41596976, Node: 41597048, Node: 41596904],
 [Node: 41597120, Node: 41597192, Node: 41597336],
 [Node: 41597552, Node: 41597624, Node: 41597696],
 [Node: 41597768, Node: 41597840, Node: 41597912]]
like image 135
JBernardo Avatar answered Sep 29 '22 08:09

JBernardo