如何设置python列表/集的最大长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17526659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a max length for a python list/set?
提问by alvas
In c/c++, we could have:
在 c/c++ 中,我们可以有:
maxnum = 10;
double xlist[maxnum];
How to set a maximum length for a python list/set?
如何设置python列表/集的最大长度?
采纳答案by Martijn Pieters
You don't and do not need to.
你不需要也不需要。
Python lists grow and shrink dynamically as needed to fit their contents. Sets are implemented as a hash table, and like Python dictionaries grow and shrink dynamically as needed to fit their contents.
Python 列表根据需要动态增长和缩小以适应其内容。集合被实现为一个哈希表,就像 Python 字典一样,根据需要动态地增长和缩小以适应它们的内容。
Perhaps you were looking for collections.deque
(which takes a maxlen
parameter) or something using a heapq
(using heapq.heappushpop()
when you have reached the maximum) instead?
也许您正在寻找collections.deque
(它需要一个maxlen
参数)或使用 a heapq
(heapq.heappushpop()
当您达到最大值时使用)代替的东西?
回答by kiriloff
Once you have your list, lst
, you can
一旦你有了你的清单lst
,你就可以
if len(lst)>10:
lst = lst[:10]
If size more than 10 elements, you truncate to first ten elements.
如果大小超过 10 个元素,则截断为前十个元素。
回答by Ashwini Chaudhary
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.
Python 不是 C++,python 是一种动态语言。集合和列表可以扩展或收缩到任何大小。
Use heapqmodule if you want x smallest or largest items from an iterable.
如果您想要可迭代对象中的 x 个最小或最大项,请使用heapq模块。
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]
从 iterable 定义的数据集中返回一个包含 n 个最小元素的列表。键,如果提供,指定一个参数的函数,用于从迭代中的每个元素中提取比较键:key=str.lower 等效于:sorted(iterable, key=key)[:n]
Or may be bisectmodule:
或者可能是二等分模块:
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.
然后使用切片或 itertools.slice
从列表中获取前 x 项。
回答by stalk
Here is extended version of python's list
. It behaves like list
, but will raise BoundExceedError
, if length is exceeded (tried in python 2.7):
这是 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)
Usage:
用法:
>>> 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]