限制 Python 列表的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40696005/
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
Limit the length of a Python list
提问by Waheed Hussain
How would I set a list that only holds up to ten elements?
我将如何设置一个最多包含十个元素的列表?
I'm obtaining input names for a list using the following statement:
我正在使用以下语句获取列表的输入名称:
ar = map(int, raw_input().split())
and would like to limit the number of inputs a user can give
并希望限制用户可以提供的输入数量
回答by Moinuddin Quadri
After getting the ar
list, you may discard the remaining items via list slicingas:
获取ar
列表后,您可以通过列表切片丢弃剩余的项目:
ar = ar[:10] # Will hold only first 10 nums
In case you also want to raise error if list has more items, you may check it's length as:
如果您还想在列表有更多项目时引发错误,您可以检查它的长度为:
if len(ar) > 10:
raise Exception('Items exceeds the maximum allowed length of 10')
Note:In case you are making the length check, you need to make it before slicing the list.
注意:如果您要进行长度检查,则需要在对列表进行切片之前进行检查。
回答by CopyPasteIt
I found this post with a google search.
我通过谷歌搜索找到了这篇文章。
Yes, the following just expands on Moinuddin Quadri's answer (which I upvoted), but heck, this is what works for my requirements!
是的,以下只是扩展了 Moinuddin Quadri 的答案(我赞成),但是哎呀,这就是我的要求!
Python Program
蟒蛇程序
def lifo_insert(item, da_mem_list):
da_mem_list.insert(0, item)
return da_mem_list[:3]
# test
lifo_list = []
lifo_list = lifo_insert('a', lifo_list)
print('1 rec:', lifo_list)
lifo_list = lifo_insert('b', lifo_list)
lifo_list = lifo_insert('c', lifo_list)
print('3 rec:', lifo_list)
lifo_list = lifo_insert('d', lifo_list)
print('ovflo:', lifo_list)
OUTPUT
输出
1 rec: ['a']
3 rec: ['c', 'b', 'a']
ovflo: ['d', 'c', 'b']
回答by sidshrivastav
You can also do something like this.
你也可以做这样的事情。
n = int(input())
a = [None] * n
It will create a list with limit n.
它将创建一个限制为 n 的列表。