简体   繁体   中英

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?

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]]

Python doesnt really do 2d arrays. Here is a better explenation

Its does lists instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM