如何设置仅包含十个元素的列表?
我使用以下语句获取列表的输入名称:
ar = map(int, raw_input().split())
Run Code Online (Sandbox Code Playgroud)
并希望限制用户可以提供的输入数量
获取ar列表后,您可以通过列表切片丢弃剩余的项目:
ar = ar[:10] # Will hold only first 10 nums
Run Code Online (Sandbox Code Playgroud)
如果你想在列表中有更多项目时提出错误,你可以检查它的长度如下:
if len(ar) > 10:
raise Exception('Items exceeds the maximum allowed length of 10')
Run Code Online (Sandbox Code Playgroud)
注意:如果要进行长度检查,则需要在切片列表之前进行检查.