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

use*_*738 8 python object

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

self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]
Run Code Online (Sandbox Code Playgroud)

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

如您所见,我对 python 很陌生。任何帮助将不胜感激。

Elm*_*lmo 6

Python 是一种动态语言,因此没有array of type.
您创建一个空的通用列表:

self.arrayOfGhosts = []
Run Code Online (Sandbox Code Playgroud)

您不关心列表的容量,因为它也是动态分配的。
您可以根据需要使用任意数量的Ghost实例填充它:

self.arrayOfGhosts.append(Ghost())
Run Code Online (Sandbox Code Playgroud)

但是,以上内容确实足够了:
如果您真的想强制此列表仅接受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')
Run Code Online (Sandbox Code Playgroud)

然后对于二维列表,您可以使用此类,例如:

self.arrayOfGhosts = []
self.arrayOfGhosts.append(GhostList())
self.arrayOfGhosts[0].append(Ghost())
Run Code Online (Sandbox Code Playgroud)


pil*_*ona 3

这些是列表,而不是数组。Python 是一种鸭子类型的语言。无论如何,列表都是异构类型的。例如。您的列表可以包含int、 、strlist、 或任何适合您喜好的内容。您不能使用库存类来限制类型,这违反了该语言的哲学。

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

self.arrayOfGhosts = []
Run Code Online (Sandbox Code Playgroud)

二维列表很简单。只是嵌套列表。

l = [[1, 2, 3], [4, 5, 6]]
l[0]  # [1, 2, 3]
l[1][2]  # 6
Run Code Online (Sandbox Code Playgroud)

如果您确实想要占位符,只需执行以下操作即可。

[[None] * 100 for i in range(100)]
Run Code Online (Sandbox Code Playgroud)

Python 没有数组,除非你的意思是array.array,无论如何,这都是针对 C 类型的。大多数时候,数组在 Python 中是错误的抽象级别。

PS 如果您正在使用xrange,那么您必须使用Python 2。除非您需要非常具体的库,否则请停止并使用Python 3。看看为什么

PPS 你用 初始化NULL,而不是0在 C++ 中。切勿用来0表示NULL.

PPPS 请参阅PEP 8,规范的 Python 风格指南。