python基础学习04

python基础语法学习-元组与切片

python基础学习04

python基础语法学习-元组与切片

元组

元组是一个不可变结构 是不允许修改的,只查询
In [164]: t = tuple()

In [165]: t
Out[165]: ()

In [166]: t = (1,2,3)

In [167]:

In [171]: t.count(1)
Out[171]: 1

In [175]: t = (1)

In [176]: t
Out[176]: 1

In [177]: t = (1,)

In [178]: t
Out[178]: (1,)

In [179]:

列表和元组的区别

list是[]号
元组是()号
list可以修改
元组不可以修改

切片使用练习

什么是切片操作?
	切片是针对索引来做的.
	seq[start:end] [staer end] 
	切片不包括end
In [186]: list
Out[186]: [1, 2, 3, 4, 5, 5]

In [187]: list[0]
Out[187]: 1

In [188]: list[0:3]
Out[188]: [1, 2, 3]

In [189]:

In [205]: list[-7:-1]
Out[205]: [71, 2, 44, 55, 88, 9]

In [206]:
	//从左往右切片,所以start要小于end
In [206]: list[12:3]
Out[206]: []
	//如果start大于end会返回一个空列表
In [207]: len(list)
Out[207]: 16

In [208]: list[12:30]
Out[208]: [55, 88, 9, 0]
	//如果start超出索引范围从0开始,end超出索引范围到len(list)结束
In [211]: list[:12]
Out[211]: [1, 2, 3, 4, 5, 5, 9, 5, 6, 71, 2, 44]

In [212]: list[12:]
Out[212]: [55, 88, 9, 0]
	//start为0的时候可以省略
	
In [213]: list[:]
Out[213]: [1, 2, 3, 4, 5, 5, 9, 5, 6, 71, 2, 44, 55, 88, 9, 0]

In [214]:
	//start为0end为-1的时候相当于xopy的效果

In [218]: list = [0,1,2,3,4,5,6,7,8,9]

In [219]: list[5:2:-1]
Out[219]: [5, 4, 3]

	//当step为负数的时候.从后往前数,此时start应小于end,否则会返回空列表
In [231]: list
Out[231]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [232]: list[1::3]
Out[232]: [1, 4, 7]

In [233]:
list中间隔了三个数.如果list[1::4]中间是隔了四个数

切片赋值

In [10]: list
Out[10]: [3, 5, 6, 3, 4, 5, 7, 8, 2, 3, 2]

In [11]: list[3:5]
Out[11]: [3, 4]

In [12]: list[3:5] = ['x','y','z']

In [13]: list
Out[13]: [3, 5, 6, 'x', 'y', 'z', 5, 7, 8, 2, 3, 2]

In [14]:

In [15]: list
Out[15]: [3, 5, 6, 3, 4, 5, 7, 8, 2, 3, 2]

In [16]: list[3:5]
Out[16]: [3, 4]

In [17]: list[3:5] = ['x']

In [18]: list
Out[18]: [3, 5, 6, 'x', 5, 7, 8, 2, 3, 2]

In [19]:
  总结:
    对切片赋值,会替换切片原来的元素
    对切片赋值,如果不连续的要两边元素个数要一致

See also