+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2020-03(70)

2020-04(60)

2020-05(24)

2020-06(39)

2020-07(23)

python(索引/切片)

发布于2019-10-27 09:44     阅读(576)     评论(0)     点赞(26)     收藏(1)


0

1

2

3

4

5

6

一.索引

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
复制代码

 

二.切片  var[start_index:end_index]

  • 注意:切出的值不包含end_index的值

1.正切

复制代码
>>> name = "xinfangshuo"
>>>
>>> name[3:6]
'fan'
>>> name[3:7]
'fang'
>>> name[0:11]
'xinfangshuo'
>>> name[0:]
'xinfangshuo'
>>> name[:]
'xinfangshuo'
复制代码

2.反切

复制代码
>>> name = "xinfangshuo"
>>> 
>>> name[:-1]
'xinfangshu'
>>> name[:-2]
'xinfangsh'
>>> name[3:-4]
'fang'
复制代码

3.跳级切

复制代码
>>> name = "xinfangshuo"
>>>
>>> name[3:7]
'fang'
>>> name[3:7:]
'fang'
>>> name[3:7:1]
'fang'
>>> name[3:7:2]
'fn'
>>> name[7:3:2]
''
>>> name[::3]
'xfgu'
复制代码

4.反跳级切

  • 从右往左切
  • start_index位置要在end_index位置的右边
复制代码
>>> name = "xinfangshuo"
>>>
>>> name[-1:-8:-2]
'ohga'
>>> name[-1:8:-2]
'o'
>>>
>>> name[1:10:-2]
''
>>> name[10:1:2]
''
>>> name[10:1:-2]
'ohgan'
复制代码

 

0

1

2

3

4

5

6

7



所属网站分类: 技术文章 > 博客

作者:9384vfnv

链接: https://www.pythonheidong.com/blog/article/146075/c5c3b046ec8c444999dd/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

26 0
收藏该文
已收藏

评论内容:(最多支持255个字符)