Python list列表index查找使用方法

admin 2014年5月13日03:43:56Python评论1,694 次浏览阅读模式


本文主要讲列表的index方法,当你需要知道某个值在列表中的索引位置时候,你可以使用index()方法,其返回值是要查值的索引。

index()方法标准格式

index()方法和列表或是其它python内置数据类型方法的调用格式一样:变量名.方法(参数),这个格式是方法调用的标准格式。

查找演示操作

>>> a = ['www','iplaypython','com']
>>> a.index('iplaypython')
1
#新建设变量名a的列表
#查找字符串‘iplaypython’在列表a中的位置
#返回1,表示要查找参数在列表中的索引下标位置是1

再来查找一个不存在的参数,看看会有什么样结果
>>> a.index('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'hello' is not in list
当查找字符串‘iplaypython’时,返回了它的索引位置;而查找'hello'时则引发了一个错误异常,并报错说'hello' is not in list,字符串'hello'不在列表中。

总结

用列表的index()方法查找参数时:如果参数存在,返回索引位置;如果参数不存在,则报错。

相关文章
weinxin
我的微信
微信扫一扫
admin
  • 本文由 发表于 2014年5月13日03:43:56
  • 转载请务必保留本文链接:https://anyun.org/a/jishuguanzhu/bianchengchalou/python/2014/0513/997.html

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: