Python 如何创建特定类型但为空的列表

Python 如何创建特定类型但为空的列表,python,object,Python,Object,如何创建特定类型对象的列表但为空?可能吗?我想创建一个对象数组(类型称为ghost),该数组稍后将包含从称为ghost的类继承的不同类型。它在C++中都非常简单,但我不确定如何在Python中实现。我试过这样的方法: self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)] class GhostList(list): def __init__(self, iterable=None):

如何创建特定类型对象的列表但为空?可能吗?我想创建一个对象数组(类型称为ghost),该数组稍后将包含从称为ghost的类继承的不同类型。它在C++中都非常简单,但我不确定如何在Python中实现。我试过这样的方法:

self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]
class GhostList(list):

    def __init__(self, iterable=None):
        """Override initializer which can accept iterable"""
        super(GhostList, self).__init__()
        if iterable:
            for item in iterable:
                self.append(item)

    def append(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).append(item)
        else:
            raise ValueError('Ghosts allowed only')

    def insert(self, index, item):
        if isinstance(item, Ghost):
            super(GhostList, self).insert(index, item)
        else:
            raise ValueError('Ghosts allowed only')

    def __add__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__add__(item)
        else:
            raise ValueError('Ghosts allowed only')

    def __iadd__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__iadd__(item)
        else:
            raise ValueError('Ghosts allowed only')
但是它已经被对象初始化了,我不需要它,有没有办法用0初始化它,但是有一个类型为Ghost的列表


正如您所看到的,我对python非常陌生。非常感谢您的帮助。

这些是列表,不是数组。Python是一种鸭子类型的语言。无论如何,列表都是异质类型的。例如您的列表可以包含一个
int
,后跟
str
,后跟
list
,或者任何适合您的内容。不能用stock类限制类型,这违反了语言的哲学

只需创建一个空列表,然后添加

self.arrayOfGhosts = []
二维列表很简单。只是嵌套列表

l = [[1, 2, 3], [4, 5, 6]]
l[0]  # [1, 2, 3]
l[1][2]  # 6
如果您真的想要占位符,只需执行以下操作

[[None] * 100 for i in range(100)]
Python没有数组,除非您指的是
array.array
,反正它是用于C-ish类型的。在Python中,数组通常是错误的抽象级别

另外,如果您使用的是
xrange
,那么您必须使用Python 2。除非您需要非常特定的库,否则请停止使用Python 3

在C++中,你用<代码> null < />代码初始化,而不是<代码> 0 。切勿使用
0
表示
NULL


p.p.p.S.请参阅规范的Python风格指南。

Python是一种动态语言,因此没有类型的
数组的概念
您可以创建一个空的常规列表,其中包含:

self.arrayOfGhosts = []
您不关心列表的容量,因为它也是动态分配的。
根据您的意愿,您可以使用任意多的
Ghost
实例来填充它:

self.arrayOfGhosts.append(Ghost())
不过,上述内容已经足够了:
如果确实希望强制此列表仅接受
重影
和继承类实例,则可以创建如下自定义列表类型:

self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]
class GhostList(list):

    def __init__(self, iterable=None):
        """Override initializer which can accept iterable"""
        super(GhostList, self).__init__()
        if iterable:
            for item in iterable:
                self.append(item)

    def append(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).append(item)
        else:
            raise ValueError('Ghosts allowed only')

    def insert(self, index, item):
        if isinstance(item, Ghost):
            super(GhostList, self).insert(index, item)
        else:
            raise ValueError('Ghosts allowed only')

    def __add__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__add__(item)
        else:
            raise ValueError('Ghosts allowed only')

    def __iadd__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__iadd__(item)
        else:
            raise ValueError('Ghosts allowed only')
对于二维列表,您可以使用如下类:

self.arrayOfGhosts = []
self.arrayOfGhosts.append(GhostList())
self.arrayOfGhosts[0].append(Ghost())

Python中的列表可以根据需要增长,它们不是固定长度,就像在C或C++中可能使用的。

因此,不需要在Python中“初始化”列表。只要在需要时创建它,然后根据需要添加到其中

您绝对不需要幽灵对象的“归零列表”,只需执行以下操作:

scary_farm = []  # This is an empty list.
ghosts = []

# .. much later down in your code

mean_ghost = Ghost(scary_level=10, voice='Booooo!')
ghosts.append(mean_ghost)

casper = Ghost(scary_level=-1, voice="I'm the friendly ghost. Hee hee!")
ghosts.append(casper)

# ... later on
scary_farm.append(ghosts) # Now you have your 2-D list

for item in scary_farm:
    for ghost in item:
        print('{0.voice}'.format(ghost))
注意,在Python中单步遍历列表或任何集合时,也不需要索引列表。在C/C++中,您可能会:

for(i = 0; i < 10; i++)
{ 
    cout << scary_farm[i] << endl;
}
(i=0;i<10;i++)的

{ 

没问题,但我还是想要二维列表,有可能吗?“[[None]*100]*100”-它不起作用,我将同一个列表复制了100次
None
,通过引用将其与另一个列表进行比较
None
总是正确的。如果它是占位符,则无论您是通过相等还是身份进行比较都无关紧要。如果您想放置半初始化的重影(并非所有代码都要初始化为有效状态)在这里,您必须使用列表理解@ USER 3623 738:考虑包含有用的评论,包括评论。停止在Python Mead中编写C代码。只要列表中的TIGY实现了你正在调用的方法,它就可以工作。不必尝试在其上加上静态类型。我更像是一个C程序员,我只需要在Python写一个项目,甚至不用写。有很多时间学习。是的,在那里,伙计,最快的绊倒方式是用一种语言写,然后翻译你最后在J'habite une rouge maison场景中…我不知道你刚才对我说的关于“rouge maison”的什么:我们很遗憾地看到,没有一个答案能找到一个涵盖所有用例的问题解决方案,还包括添加
。插入
。\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,如果需要的话。这就像一门大炮被用来在纸上打孔一样。@BurhanKhalid看到答案的第一部分清楚地说它不是必需的。第二部分只是证明在某种程度上,类型强制在Python中是可能的。顺便说一句,
isinstance
在Python中很少是答案。请看。@BurhanKhalid它实际上是,三思而后行,有人困惑吗