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

2024-05-20 18:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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


Tags: 对象方法inself类型列表for数组
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())

这些是列表,不是数组。Python是一种duck类型的语言。无论如何,列表都是异种类型的。例如。您的列表可以包含一个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。See why

在C++中,用^ {< CD6>}初始化,而不是^ {< CD7>}。不要用0来表示NULL

p.p.p.S.参见PEP 8,规范的Python样式指南。

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

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

相关问题 更多 >