我正在尝试创建名为map2d的The following command must be run outside of the IPython shell:
$ pip install spark
The Python package manager (pip) can only be used from outside of IPython.
Please reissue the `pip` command in a separate terminal or command prompt.
对象的2d子类。我希望能够初始化list
并获得一个定义大小的二维数组。
E.g,
map2d
输出
class map2d(list):
def __init__(self,x,y):
# Magic code that makes this work
Map = map2d(3,2)
print(Map)
我尝试过什么
[[None, None], [None,None], [None,None]]
我知道这可能是对神圣事物的一种歪曲,但这对我来说是有意义的。
提前致谢,
约翰
答案 0 :(得分:1)
如果您只是在列表中创建列表,则无需使用类:
def map2d(x, y):
return [[None for _ in range(y)] for _ in range(x)]
print(map2d(3, 2)) # [[None, None], [None,None], [None,None]]
这将为您提供所需的输出。
另请注意,如果您要自定义打印类的方式,则应使用方法__str__
,例如:
class Example:
def __str__(self):
return "Example Class Object"
print(Example()) # Example Class Object
答案 1 :(得分:1)
self
没有什么神奇之处。当您向self
分配任何内容时,例如self = whatever
用于如何在Python中使用赋值:现在self
指的是引用的任何对象whatever
。作业永远不会改变。您需要使用mutator方法,例如.append
或.extend
或基于索引/切片的分配。这是一个简单的方法:
In [1]: class map2d(list):
...: def __init__(self,x,y):
...: for _ in range(x):
...: r = []
...: self.append(r)
...: for _ in range(y):
...: r.append(None)
...:
In [2]: map2d(2,3)
Out[2]: [[None, None, None], [None, None, None]]
但是,我认为没有充分的理由为此使用继承。只需创建辅助函数:
In [3]: def map2d(x,y):
...: return [[None for _ in range(y)] for _ in range(x)]
...:
In [4]: map2d(2,3)
Out[4]: [[None, None, None], [None, None, None]]
注意列表不是数组,列表没有“维度”,它们只有一个长度。
如果你真的想防止负面索引,你可以这样做:
In [10]: class MyList(list):
...: def __getitem__(self, item):
...: if isinstance(item, int) and item < 0:
...: raise TypeError("MyList indices must be positive")
...: self.__getitem__(item)
...:
In [11]: x = MyList()
In [12]: x.append(3)
In [13]: x[-1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-c30dd0d358dc> in <module>()
----> 1 x[-1]
<ipython-input-10-f2169a236374> in __getitem__(self, item)
2 def __getitem__(self, item):
3 if isinstance(item, int) and item < 0:
----> 4 raise TypeError("MyList indices must be positive")
5 self.__getitem(item)
6
TypeError: MyList indices must be positive