如何为python列表/集设置最大长度?

2024-07-08 09:44:31 发布

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

在c/c++中,我们可以有:

maxnum = 10;
double xlist[maxnum];

如何为python列表/集设置最大长度?


Tags: 列表doublexlistmaxnum
3条回答

这是python的list的扩展版本。它的行为类似于list,但是如果超过长度,它将提高BoundExceedError(在python 2.7中尝试过):

class BoundExceedError(Exception):
    pass


class BoundList(list):
    def __init__(self, *args, **kwargs):
        self.length = kwargs.pop('length', None)
        super(BoundList, self).__init__(*args, **kwargs)

    def _check_item_bound(self):
        if self.length and len(self) >= self.length:
            raise BoundExceedError()

    def _check_list_bound(self, L):
        if self.length and len(self) + len(L) > self.length:
            raise BoundExceedError()

    def append(self, x):
        self._check_item_bound()
        return super(BoundList, self).append(x)

    def extend(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).extend(L)

    def insert(self, i, x):
        self._check_item_bound()
        return super(BoundList, self).insert(i, x)

    def __add__(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).__add__(L)

    def __iadd__(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).__iadd__(L)

    def __setslice__(self, *args, **kwargs):
        if len(args) > 2 and self.length:
            left, right, L = args[0], args[1], args[2]
            if right > self.length:
                if left + len(L) > self.length:
                    raise BoundExceedError()
            else:
                len_del = (right - left)
                len_add = len(L)
                if len(self) - len_del + len_add > self.length:
                    raise BoundExceedError()
        return super(BoundList, self).__setslice__(*args, **kwargs)

用法

>>> l = BoundList(length=10)
>>> l.extend([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> # now all these attempts will raise BoundExceedError:
>>> l.append(11)
>>> l.insert(0, 11)
>>> l.extend([11])
>>> l += [11]
>>> l + [11]
>>> l[len(l):] = [11]

你不需要也不需要。

Python列表根据需要动态增长和收缩,以适应其内容。集合被实现为一个哈希表,并且像Python字典一样,根据需要动态地增长和收缩以适应其内容。

或许你在寻找^{}(它接受一个maxlen参数)或者使用^{}(当你达到最大值时使用heapq.heappushpop())的东西?

一旦你有了清单,lst,你就可以

if len(lst)>10:
    lst = lst[:10]

如果大小超过10个元素,则截断为前10个元素。

相关问题 更多 >

    热门问题