码迷,mamicode.com
首页 > 编程语言 > 详细

python学习(索引)

时间:2019-10-22 10:38:48      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:shu   module   mos   font   key   div   ast   strong   round   

一.索引

1.索引值从左到右-->从0开始,索引值从右到左-->从-1开始

  • 取值格式var[index]
>>> name = "xinfangshuo"
>>>
>>> name[0]
x
>>> name[5]
n
>>> name[-1]
o
>>> name[-2]
u

2.注意:整型int和字典dict和集合set不支持索引取值

 

>>> age = 123
>>>
>>> age[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int object has no attribute __getitem__
>>> age = "123"
>>> age[1]
2
>>> name = {"name1":"zhangsan","name2":"lisi","name3":"wangwu"}
>>>
>>> name[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
>>>
>>> set = {"zhangsan","lisi","wangwu"}
>>>
>>> set[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set object does not support indexing

 

3.多维数组/列表,索引取值

"""多维数组,索引取值"""
>>> name = ("zhangsan","lisi","wangwu","zhaoliu","wangba",("zhengying","lizhipeng","lvlinlin"))
>>>
>>> name[5][1]
lizhipeng
>>>
>>> list = [1,2,3,4,[5,6,7,[8,9,0]]]
>>>
>>> list[4][3][1]
9
>>> list[-1][-1][-2]
9

 

python学习(索引)

标签:shu   module   mos   font   key   div   ast   strong   round   

原文地址:https://www.cnblogs.com/Mr-ZY/p/11718154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!