Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否创建二维数组列表对象?_Python_Python 3.x_List_Initialization - Fatal编程技术网

Python 是否创建二维数组列表对象?

Python 是否创建二维数组列表对象?,python,python-3.x,list,initialization,Python,Python 3.x,List,Initialization,我试图为列表对象创建一个名为map2d的2d子类。我希望能够初始化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]] 我尝试的 class map2d(list):

我试图为
列表
对象创建一个名为map2d的2d子类。我希望能够初始化
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]]
我尝试的

class map2d(list):
    def __init__(self,x,y):
        self = [[None for _ in range(y)] for _ in range(x)]
我知道这可能是对一切神圣事物的歪曲,但对我来说是有道理的

提前感谢,


John

如果只是在列表中创建列表,则无需使用类:

def map2d(x, y):
    return [[None for _ in range(y)] for _ in range(x)]

print(map2d(3, 2)) # [[None, None], [None,None], [None,None]]
这将为您提供所需的输出

另外,请注意,如果您希望自定义类的打印方式,则应使用方法
\uuu str\uu
,例如:

class Example:
    def __str__(self):
        return "Example Class Object"

print(Example()) # Example Class Object

如果只是在列表中创建列表,则无需使用类:

def map2d(x, y):
    return [[None for _ in range(y)] for _ in range(x)]

print(map2d(3, 2)) # [[None, None], [None,None], [None,None]]
这将为您提供所需的输出

另外,请注意,如果您希望自定义类的打印方式,则应使用方法
\uuu str\uu
,例如:

class Example:
    def __str__(self):
        return "Example Class Object"

print(Example()) # Example Class Object

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
[10]中的
:类MyList(列表):
…:def_uugetItem_uu(self,item):
…:如果isinstance(项,int)和项<0:
…:raise TypeError(“MyList索引必须为正”)
…:self.\uuuu获取项目\uuuuuu(项目)
...:
在[11]中:x=MyList()
在[12]中:x.append(3)
In[13]:x[-1]
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 x[-1]
在_u获取项目_;(自我,项目)
2定义获取项目(自身,项目):
3如果isinstance(项目,int)和项目<0:
---->4 raise TypeError(“MyList索引必须为正”)
5自取项目(项目)
6.
TypeError:MyList索引必须为正

自我没有什么神奇之处。当您将任何内容分配给
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
[10]中的
:类MyList(列表):
…:def_uugetItem_uu(self,item):
…:如果isinstance(项,int)和项<0:
…:raise TypeError(“MyList索引必须为正”)
…:self.\uuuu获取项目\uuuuuu(项目)
...:
在[11]中:x=MyList()
在[12]中:x.append(3)
In[13]:x[-1]
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 x[-1]
在_u获取项目_;(自我,项目)
2定义获取项目(自身,项目):
3如果isinstance(项目,int)和项目<0:
---->4 raise TypeError(“MyList索引必须为正”)
5自取项目(项目)
6.
TypeError:MyList索引必须为正

@JhonAZ1你有什么问题?@MauricioCortazar我刚得到一个空的list@JhonAZ1你的问题是什么?@MauricioCortazar我只是得到一个空列表我想使用类的原因是为了防止负面索引,并且能够将所有这些放在一起似乎很好,那么你应该从@juanpa.arrivillaga检查答案:)我想使用类的原因是为了防止负面索引,并且能够将所有这些放在一起似乎很好,然后您应该从@juanpa.arrivillaga:)查看答案谢谢。我想要一个对象的原因是为了防止负索引。@JohnAZ1 a
list
已经是一个对象了。在Python中,一切都是一个对象。如果您希望子类化以防止负面索引,则需要重写
\uuu getitem\uuuuuuuu
而不是
\uuuuu init\uuuuuu
谢谢。我想要一个对象的原因是为了防止负索引。@JohnAZ1 a
list
已经是一个对象了。在Python中,一切都是一个对象。如果希望子类化以防止负面索引,则需要重写
\uuuu getitem\uuuuuuuu
而不是
\uuuuu init\uuuuuu