我正在将一些
java代码转换为python代码,我最终难以理解如何将
Java中的2D对象数组转换为python.
Java代码:
- private Node nodes[][] = new Node[rows][columns];
我怎么能在python中这样做?
解决方法
我想这就是你想要的
- nodes = [[Node() for j in range(cols)] for i in range(rows)]
但是,初始化列表并不总是一个好习惯.对于矩阵,它可能是有道理的.
如果你想知道:关于list comprehensions的文档
演示代码:
- >>> 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]]