简体   繁体   English

检查列表索引是否存在

[英]To check whether index of list exists

Is there any solution to check whether index of list exists? 有什么解决方案来检查列表索引是否存在?

Other than: 以外:

  1. using len(list) 使用len(list)

  2. using 使用

     try: ... except IndexError: ... 

As dict has a dict.has_key(key) to check whether key exists, is there any method to check index for list? 由于dict有dict.has_key(key)来检查键是否存在,是否有任何方法来检查列表的索引?

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. 必须进行成员资格测试才能确定某个密钥是否有效存在,因为扫描所有密钥的效率很低。

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. len(somelist)便宜(长度缓存列表对象),所以index < len(somelist)是测试一个索引是否存在,用异常处理有很大回落,如果你预计,恒生指数将在列表中方式大部分时间都是边界。

You could use list comprehensions. 您可以使用列表推导。

index in [someList.index(item) for item in someList]:

This will return true if there are at least index items in the list. 如果列表中至少有index项,则将返回true。

For dictionaries you could do something similar: 对于字典,您可以执行类似的操作:

index in [someDictionary.keys().index(item) for item in someDictionary.keys()]

It's worth pointing out that this really is a moot point since using len(list) or try ... except works perfectly well. 值得指出的是,这确实是有争议的,因为使用len(list)try ... except效果很好。 But hey, you asked for another way, so here's another way. 但是,嘿,您要求另一种方式,所以这是另一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM