索引+分片
1、索引
(1)greeting=’hello’ greeting[0] h
(2)’hello’[0] h
2、分片(取左不取右)
a=[1,2,3,4,5]
a[1:3] a[1]=2,a[2]=3 [2,3]
a[-3,-1] a[-3]=3, a[-2]=4 [3,4]
a[3:1] [] 左边数在右边数后面,则为空
a[:] 取整个数组
加步长的分片
a[0:5:2] [1,3,5]
a[::3] [1,4]
a[3::-1] [4,3,2,1]
运算
1、序列相加
[1,2,3]+[4,5,6]=[1,2,3,4,5,6 ] 相加数据类型要一致,单独赋值不需要一致
2、乘法
‘hello’*5 ‘hello hello hello hello hello’
[7]*3 [7,7,7]
3、成员资格
test=’hello,world’
‘h’ in test true
a=[1,2,3,4,5]
1 in a true
4、长度,最大值,最小值
a=[1,2,3,4,5]
len(a) 5
max(a) 5
min(a) 1
max(1,7,3,4) 7
列表
1、元素赋值
a=[1,2,3]
a[1]=10 [1,10,3]
a[2]=’aa’ [1,10,’aa’]
type(a[2]) <class ‘str’>
2、增加元素
a=[1,2,3] a.append(5) [1,2,3,5]
3、删除元素
a=[1,2,3,5] del a[1] [1,3,5]
4、分片赋值
a= list(‘今天下雨’) [‘今’,’天’,’下’,’雨’]
a[1:]=list(‘hello’) [‘今’,’h’,’e’,’l’,’l’,’o’]
a[1:1]=list(‘aa’) [‘今’,’a’,’a’,’h’,’e’,’l’,’l’,’o’]
a[0:3]=[] [’h’,’e’,’l’,’l’,’o’]
del a[1:2] [’h’,’’l’,’l’,’o’]
嵌套列表
m=[1,2,3]
n=list('hello')
x=[m,n]
>>> x
[[1, 2, 3], ['h', 'e', 'l', 'l', 'o']]
列表方法(*)
列表.方法(对象)
1、list.append(obj) 加新对象
a=[1,2,3]
a.append(5) [1,2,3,5]
2、list.count(obj) 计数
a=list('hello,world!')
print('字母O的个数: ',a.count('o'))
字母O的个数: 2
['a','b','c'].count('b') 1
b=[1,2,[1,2],3,[1,2]]
print('[1,2]的个数为',b.count([1,2]))
[1,2]的个数为 2
3、list.extend(obj) 加序列
m=['abc','qq']
n=[12,[3,4],'aa']
m.extend(n) ['abc', 'qq', 12, [3, 4], 'aa']
m=m+n ['abc', 'qq', 12, [3, 4], 'aa']
4、list.index(obj) 查到某个值第一个匹配的位置
a=[3,1,3,2,5,33,1]
print(a.index(1)) 1
a=['a','b','c']
b=[1,2,3]
>>> b[a.index('b')] 2
5、list.insert(obj) 插入元素
m=[1,3,5,7,9]
m.insert(2,2) [1, 3, 2, 5, 7, 9]
6、list.pop(obj) 移除元素
m=[1,3,5,7,9]
m.pop(1) 3 除none方法外唯一一个有返回值
print(m) [1, 5, 7, 9]
栈的原理类似于堆盘子,后进先出,最后放入又最先被移出的,称为LIFO
Python没有入栈方法,可以用append代替;出栈(pop)
m=[1,3,5,7,9]
m.append(m.pop(3)) m=[1, 3, 5, 9, 7]
7、list.remove(obj) 移出某个值第一个匹配项
m=['abc',1,2,'aa','abc']
m.remove('abc')
>>> m
[1, 2, 'aa', 'abc']
8、list. reverse () 反向列表
a=[1,3,5,2]
a.reverse()
>>> a
[2, 5, 3, 1]
list(reversed(a))
[1, 3, 5, 2]
9、list. sort () 排序
a=[1,3,5,2]
a.sort()
>>> a
[1, 2, 3, 5]
c=sorted(a) 列表在方法里面用sorted(list)
>>> c
[1, 2, 3, 5]
sorted('hello')
['e', 'h', 'l', 'l', 'o']
10、list. clear () 清空列表
a=[1,3,5,2]
a.clear()
>>> a
[]
11、list. copy ()
a=[1,2,3]
b=a.copy()
>>> b
[1, 2, 3]
12、高级排序(两参数key和reverse)
m=['asd','sdss','a','wwws']
m.sort(key=len,reverse=True)
>>> m
['sdss', 'wwws', 'asd', 'a']
元祖(*)
和列表相似,但是元祖不能修改,所以更安全,因此能使用元祖尽量使用元祖
1、tuple 把序列转化为元祖,如果是元祖,参数变为原样
a='hello'
tuple(a)
('h', 'e', 'l', 'l', 'o')
tuple(['aa','bb'])
('aa', 'bb')
2、访问元祖
m=(1,4,5,6)
m[1] 4
m[1:3] (4, 5)
m[0:5:2] (1, 5)
3、修改元祖(可以连接元祖)
m=(1,4,5,6)
n=('a','b')
m+n
(1, 4, 5, 6, 'a', 'b')
4、删除元祖(只能删除整个元祖)
del m 或 del(m)
>>> m
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
m
NameError: name 'm' is not defined
5、元祖索引,截取
m=(1,4,5,6)
m[1] 4
m[1:3] (4, 5)
m[0:5:2] (1, 5)
6、元祖内置函数
m=('aa','sss','d')
>>> len(m) 3
>>> max(m) 'sss'
>>> min(m) 'aa'
7、列表与元祖并行(元祖的值不能修改,但元祖内列表的值可以修改)
m=('a','b',['A','B'])
m[2][0]='x'
m[2][1]='y'
m
('a', 'b', ['x', 'y'])