一. 索引
1.索引值以 0 为开始值,-1 为从末尾的开始位置。
取值格式var[index]
字符串索引
name="hello_shenzhen" print(name[0]) print(name[1]) print(name[-1]) print(name[-2])
列表索引
phone=['huawei','sanxing','apple','xiaomi','zhongxin'] print(phone[0]) print(phone[1]) print(phone[-1]) print(phone[-2])
注意:整型int和字典dict和集合set不支持索引取值
3.多维数组,索引取值(通过索引的基础上再次索引)
name=("zhangsan","lisi",("liudehua","telangpu","tainmao"),"wangwu","zhaoliu","wangba") print(name[2][-1])
phone=['huawei','sanxing','apple','xiaomi','zhongxin',['huojiya','xiaolingtong']] print(phone[0]) print(phone[1]) print(phone[-1]) print(phone[-2]) print(phone[5][-1])
二.切片 var[start_index:end_index]
注意:切出的值不包含end_index的值
正切
name="shenzhenwuya"
print(name[2:6])#取值从3—6 结果:enzh print(name[3:7]) 结果:nzhe print(name[0:11]) 结果:shenzhenwuy print(name[0:]) 结果:shenzhenwuya print(name[:]) 结果:shenzhenwuya
反切
name="shenzhenwuya" print(name[:-1]) 结果:shenzhenwuy print(name[:-2]) 结果:shenzhenwu print(name[4:-4]) 结果:zhen
跳级切
name="shenzhenwuya" print(name[1:8:]) 结果:henzhen print(name[1:8:1]) 结果:henzhen print(name[1:8:2]) 结果:hnhn print(name[1:8:3]) 结果:hzn print(name[::2]) 结果:sezewy
4.反跳级切
name="shenzhenwuya" print(name[-12:-4:]) 结果:shenzhen print(name[-12:-4:1]) 结果:shenzhen print(name[-12:-4:2]) 结果:seze print(name[-12:-4:3]) 结果:sne print(name[::3]) 结果:sneu
题目:给定一个列表a=[1,2,3,4],请给出一个切片表达式使用列表翻转为[4,3,2,1]