Python——索引与切片

#索引与切片
##1.序列 序列:list,tuple,str 其中list是可变序列 typle,str是不可变序列
#修改序列的值
list = [3,4,5]
tup = (3,4,5)
str = '345'
list[1] = 99
list
output:[3, 99, 5]

tup[1] = 99
tup
  Output:TypeError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 tup[1] = 99
      2 tup

TypeError: 'tuple' object does not support item assignment

str[1] = 'y'
str

 Output: 
TypeError                                 Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 str[1] = 'y'
      2 str

TypeError: 'str' object does not support item assignment
!!!!此处不是代码错误,纯纯为了演示不可变序列不能修改序列的值
###2.索引
list=[1,2,3,4,5,[1,2,3,4,5]]
print(list)
print(list[0],list[1])
###python中的索引是从0开始的,list[0]代表第一个索引,list[1]代表第二个索引
 Output:   [1, 2, 3, 4, 5, [1, 2, 3, 4, 5]]
  1 2
len(list)
Output:
2 list=[1,2,3,4,5,[1,2,3,4,5]] print(list) print(list[-1],list[-2]) ###倒数第二个数用list[-1]表示,倒数第二个数用list[-2]表示 Output: [1, 2, 3, 4, 5, [1, 2, 3, 4, 5]] [1, 2, 3, 4, 5] 5 tup=['a','b','c','d'] print(tup[2],tup[-1])
Output:c d
#字符串也是索引 str='abcdefg' print(st[0],st[-2]) Output:a f

 

 

###3.切片 切片用:表示 切片是一个左闭又开的区间
list=[1,2,3,4,5,[1,2,3,4,5]]
print(list[2:3])#索引2到索引3,但不包含索引3
print(list[:2])#索引0到索引2,但不包含索引2
print(list[1:])#索引1到最后一个元素,且包含最后一个元素
print(list[1:-1])#索引1到最后一个元素,但不包括最后一个元素
  Output:  [3]
[1, 2]
[2, 3, 4, 5, [1, 2, 3, 4, 5]]
[2, 3, 4, 5]
tup=['a','b','c','d']
print(tup[1:3])
print(tup[0:])
print(tup[0:3])
  Output: ['b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c']
str='abcdefg'
print(str[0:])
print(str[0:6])
print(str[1:4])
  Output: abcdefg
abcdef
bcd

 

 
###4.步长
list=[10,20,30,40,50,60,70,80,90]
print(list[::3])
###list[a:b:n]  对于list序列,从索引a至索引b,但不包含索引b,其中间隔为n(步长) 
  Output: [10, 40, 70]

###列表的常用方法
list=[10,20,30,40,50,60,70,80,90] print(len(list))###长度 Output:9 list.append(99) list.append(['a','b'])####append是可以直接在原数据后边➕列表 print(list) Output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 99, ['a', 'b']] list=[10,20,30,40,50,60,70,80,90] list.extend(['a','b'])###在原数据后方直接追加另一个序列中的多个值 print(list) Output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 'a', 'b'] list=[10,20,30,40,50,60,70,80,90] list.insert(2,1000) print(list) Output: [10, 20, 1000, 30, 40, 50, 60, 70, 80, 90]

 


 

posted @ 2022-09-21 18:52  肚肚杜杜  阅读(289)  评论(0编辑  收藏  举报