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]

undefined

tup[1] = 99
tup
Output:TypeError                                 Traceback (most recent call last)
Input In [5], in ()
      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

undefined

###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]

undefined

###列表的常用方法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]

undefined

Original: https://www.cnblogs.com/dd0016/p/16716707.html
Author: 肚肚杜杜
Title: Python——索引与切片

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/714120/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球