Python—序列通用操作
一 序列的通用操作
1 判断元素是否在序列之内:
x in s x not in s
>>>l = [1, 2, 3, 4]
>>>1 in l
True
>>>2 not in l
False
2 连接序列
s1 + s2
>>>l = [1, 2, 3, 4]
>>>s2 = [5, 6, 7, 8]
>>>l + s2
[1, 2, 3, 4, 5, 6, 7, 8]
3 重复序列
s * n
>>>l = [1, 2, 3, 4]
>>>l * 2
[1, 2, 3, 4, 1, 2, 3, 4]
4 按下标索引访问元素
s[i] 下标索引是从0开始的
>>>l = [1, 2, 3, 4]
>>>l[1]
2
>>>l[3]
4
5 访问指定索引范围
l[i: j]
>>>l = [1, 2, 3, 4]
>>>l[2:4]
[3,4]
>>>l[:] #没有指定起始位置和终止位时,代表取所有值
[1, 2, 3, 4]
6 按步长值访问指定索引范围
l[i: j: k]
>>>l = [1, 2, 3, 4]
>>>l[::2]
[1, 3]
7 获取系列长度
len(s)
>>>l = [1, 2, 3, 4]
>>>len(l)
4
8 获取最大值 和最小值
max(s) ————-最大值
min(s) ————-最小值
9 统计综合
sum(s)
>>>l = [1, 2, 3, 4]
>>>sum(l)
10
10 检索某一值出现的第一次下标
s.index(x)
>>>l = [1, 2, 3, 4]
>>>l.index(3)
2
>>>str1 = 'acdefghijk' #字符串
>>>str1.index('a')
0
11 统计某个值出现的次数
s.count(x)
>>>str1 = 'aaabbdea'
>>>str1.count('a')
4
二 可变序列通用操作
1 改变某个元素的值
s[i] = k
>>>l = [1, 2, 3, 4]
>>>l[1] = 0
>>>l
[1, 0 ,3, 4]
2 改变特定范围内的元素值
(1) s[i:k] = t (t要求是一个可迭代的对象)
>>>l = [1, 2, 3, 4]
>>>l[1:2] = [7, 8, 9]
>>>l
[1, 7, 8, 9, 3, 4]
>>>l[1:3] = 'abc'
>>>l
[1, 'a', 'b', 'c', 9, 3, 4]
>>>l[2:3] = 1 #1不是一个可迭代的对象那个
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only assign an iterable
>>>l[2:3] = [1] #列表是可迭代对象
>>>l
[1, 'a', 1, 'c', 9, 3, 4]
(2) s[i:k:j] = t (按步长值替换值时,同样要求t是一个可迭代的对象,并且t中元素个数要与被替换的元素个数相同)
>>>l = [1, 2, 3, 4, 5]
>>>l[::2] = ['a', 'b', 'c'] #
>>>l
['a', 2, 'b', 4, 'c']
>>>l[::2] = [1, 2]
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: attempt to assign sequence of size 2 to extended slice of size 3
3 删除元素
del s[i]
del s[i:j] (等同于是s[i:j] = [] )
del s[i:j:k]
del s 删除整个序列
s.remove(x) 删除第一个匹配x的值
>>>l = [1, 2, 3, 4]
>>>del l[2]
>>>l
[1, 2, 4]
>>>l.remove(4)
>>>l
[1, 2]
4 清空序列
s.clear()
>>>l = [1, 2, 3, 4]
>>>l.clear()
>>>l
[]
5 追加一个元素
s.append(x)
>>>l = [1, 2, 3, 4]
>>>l.append(5)
>>>l
[1, 2, 3, 4, 5]
6 插入元素
s.insert(i, x) 第一个参数为索引,第二个为插入的值
>>>l = [1, 2, 3, 4]
>>>l.insert(3, 0)
>>>l
[1, 2, 3, 0, 4]
7 扩充序列 同时追加多个元素
s.extend(s2)
>>>l.extend([0, 9, 8])
>>>l
[1, 2, 3, 0, 4, 0, 9, 8]
8 弹出元素
s.pop(i) 弹出索引为i的值,没有指明i时,默认弹出最后一个值,有返回值,返回值为弹出的值
>>>l = [1, 2, 3, 4]
>>>a = l.pop(0)
>>>a
1
>>>l
[2, 3, 4]
>>>l.pop()
>>>l
[2, 3]
9 反转序列
s.reverse() 只影响原序列s,没有返回值
>>>l = [1, 2, 3, 4]
>>>a = l.reverse()
>>>a
#没有返回值,所以为空
>>>l
[4, 3, 2, 1]
小结
- 以上是自己学python时的一些笔记,感觉写在本上不方便,正好利用闲暇时间腾到csdn上。
- 自己的总结,如果有那些地方不合理或有有误,请指正。
- 知识体系图:[Python3基础数据类型