检查列表索引是否存在

检查列表索引是否存在

问题描述:

有什么办法可以检查列表的索引是否存在?

Is there any solution to check whether index of list exists?

除:

  1. 使用len(list)

使用

try:
   ...
except IndexError:
   ...

由于dict有一个dict.has_key(key)来检查键是否存在,是否有任何方法可以检查列表的索引?

As dict has a dict.has_key(key) to check whether key exists, is there any method to check index for list?

不,没有其他方法可以测试索引是否存在.

No, there are no additional methods to test if an index exists.

字典键不容易预测;您必须进行成员资格测试,以确定某个键是否有效存在,因为扫描所有键的效率很低.

Dictionary keys are not easily predicted; you have to have a membership test to determine if a key exists efficiently, as scanning through all keys would be inefficient.

列表不存在该问题; len(somelist)很便宜(长度缓存在列表对象上),所以index < len(somelist) 测试索引是否存在的方法,如果您期望索引是大部分时间都在列表边界内.

Lists do not suffer from that problem; len(somelist) is cheap (the length is cached on the list object), so index < len(somelist) is the way to test if an index exists, with exception handling a great fallback if you expect the index to be within the list boundaries most of the time.