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

时间:2014-06-11 10:40:07

标签: python object

如何创建特定类型对象的列表但是为空?可能吗?我想创建一个对象数组(该类型称为Ghosts),后来将包含从名为Ghosts的一个类继承的不同类型。它在C ++中非常简单,但我不确定如何在python中这样做。我试过这样的事情:

self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]

但它已经被对象初始化了,我不需要它,有没有办法将它初始化为0但是有一个Ghost类型的列表?

如你所见,我对python很陌生。任何帮助将受到高度赞赏。

3 个答案:

答案 0 :(得分:4)

这些是列表,而不是数组。 Python是一种鸭式语言。无论如何,列表是异质类型的。例如。您的列表可以包含int,后跟str,然后是list,或者您喜欢的任何内容。您不能使用库存类限制类型,而且这种类型与语言的哲学相悖。

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

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中错误的抽象级别。

P.S。如果您正在使用xrange,则必须使用Python 2.除非您需要非常具体的库,否则请停止并使用Python 3. See why

P.P.S。您使用NULL进行初始化,而不是使用C ++中的0进行初始化。切勿使用0来表示NULL

P.P.P.S。请参阅PEP 8,规范的Python样式指南。

答案 1 :(得分:3)

Python是一种动态语言,因此没有array of type的概念 您可以使用以下命令创建一个空通用列表:

self.arrayOfGhosts = []

您不关心列表的容量,因为它也是动态分配的 您可以根据需要填充尽可能多的Ghost个实例:

self.arrayOfGhosts.append(Ghost())

上述情况确实足够了:
如果您确实要强制执行此列表以仅接受Ghost并继承类实例,则可以创建如下自定义列表类型:

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())

答案 2 :(得分:1)

Python中的列表可以根据需要增长,它们的长度不像C或C ++中那样固定。

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

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

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;
}

但这在Python中不是必需的,因为集合类型可以直接迭代。

相关问题