19

In c/c++, we could have:

maxnum = 10;
double xlist[maxnum];

How to set a maximum length for a python list/set?

4

5 回答 5

25

你不需要也不需要。

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

也许您正在寻找collections.deque(它需要一个maxlen参数)或使用 a 的东西heapqheapq.heappushpop()当您达到最大值时使用)?

于 2013-07-08T12:33:22.017 回答
11

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

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]
于 2013-07-08T20:46:33.473 回答
10

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

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

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

于 2013-07-08T12:33:40.830 回答
3

You can't, lists and sets are dynamic in nature and can grow to any size.

Python is not c++, python is a dynamic language. Sets and list can expand or shrink to any size.

Use heapq module if you want x smallest or largest items from an iterable.

heapq.nsmallest(n, iterable[, key])

Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key)[:n]

Or may be bisect module:

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.

Then use slicing or itertools.slice to get top x items from the list.

于 2013-07-08T12:33:49.973 回答
0

你可以使用这个首先分配内存的解决方案

[0] * maxnum

或者

[a sample of your object] * maxnum

请注意,如果附加超过列表的最大大小,此解决方案不会引发诸如 c++ 语言之类的错误

于 2021-09-20T13:33:36.473 回答