2D array of objects in Python

I am converting some java code into python code, and I ended up with how to convert a 2D array of objects in Java to python.

Java Code:

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

How do I do this in python?

+6
source share
2 answers

I think you want

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

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

If you are interested: List comprehension documentation

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]] 
+10
source

Python really does not make 2d arrays. Here is the best explanation

Instead, he makes lists

0
source

Source: https://habr.com/ru/post/891359/


All Articles