简体   繁体   English

Python中的2D对象数组

[英]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代码转换为python代码,我最终难以理解如何将Java中的2D对象数组转换为python。

Java code: Java代码:

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

How would I do this in python? 我怎么能在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. Python并不真正做2D阵列。 Here is a better explenation 这是一个更好的表达方式

Its does lists instead 它确实列出了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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