限制Python列表的长度 [英] Limit the length of a Python list

查看:1888
本文介绍了限制Python列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何设置一个最多包含十个元素的列表?

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

推荐答案

获得ar列表后,您可以通过 list slicing 将其余项丢弃为:

After getting the ar list, you may discard the remaining items via list slicing as:

 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.

这篇关于限制Python列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆