检查列表索引是否存在 [英] To check whether index of list exists

查看:80
本文介绍了检查列表索引是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于检查列表索引是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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