Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
限制Python列表的长度_Python_List_Limit - Fatal编程技术网

限制Python列表的长度

限制Python列表的长度,python,list,limit,Python,List,Limit,如何设置最多只能容纳十个元素的列表 我使用以下语句获取列表的输入名称: ar = map(int, raw_input().split()) 并且要限制用户可以提供的输入数量,在获得ar列表后,您可以通过列表切片丢弃剩余的项目,如下所示: 若您还希望在列表中包含更多项时引发错误,则可以检查其长度,如下所示: if len(ar) > 10: raise Exception('Items exceeds the maximum allowed length of 10')

如何设置最多只能容纳十个元素的列表

我使用以下语句获取列表的输入名称:

ar = map(int, raw_input().split())

并且要限制用户可以提供的输入数量,在获得
ar
列表后,您可以通过列表切片丢弃剩余的项目,如下所示:

若您还希望在列表中包含更多项时引发错误,则可以检查其长度,如下所示:

 if len(ar) > 10:
      raise Exception('Items exceeds the maximum allowed length of 10')

注意:如果要进行长度检查,则需要在对列表进行切片之前进行长度检查。

您也可以这样做

n = int(input())
a = [None] * n

它将创建一个限制为n的列表。

我通过谷歌搜索找到了这篇文章

是的,下面只是对Moinuddin Quadri的答案(我投了更高的票)进行了扩展,但见鬼,这正是适合我的要求的东西

Python程序

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)
输出

1 rec: ['a']
3 rec: ['c', 'b', 'a']
ovflo: ['d', 'c', 'b']

如果要继续向列表中添加项目,但只返回最近的5个项目:

list1 = ["a1", "b1", "c1", "d1", "e1"]
list1.append("f1")
list1[-5:]

你想阻止用户,还是事后告诉他们有太多的价值?或者忽略额外的值,可能会给出这样一条消息?为什么要在输入名称时转换为整数???
list1 = ["a1", "b1", "c1", "d1", "e1"]
list1.append("f1")
list1[-5:]