python学习-序列操作符及常用方法
序列操作符及常用方法
在Python中,序列(如列表、元组、字符串)支持多种操作符和方法,以下是一些常用的序列操作符及方法:
操作符
- 索引操作符 []- 获取序列中的单个元素。seq = [1, 2, 3, 4] print(seq[0]) # 输出 1
- 切片操作符 [:]- 获取序列中的一个子序列。seq = [1, 2, 3, 4] print(seq[1:3]) # 输出 [2, 3]
- 连接操作符 +- 连接两个序列。seq1 = [1, 2, 3] seq2 = [4, 5] print(seq1 + seq2) # 输出 [1, 2, 3, 4, 5]
- 重复操作符 *- 将序列重复指定的次数。seq = [1, 2] print(seq * 3) # 输出 [1, 2, 1, 2, 1, 2]
- 成员资格操作符 in- 检查元素是否存在于序列中。seq = [1, 2, 3] print(2 in seq) # 输出 True
- 成员资格操作符 not in- 检查元素是否不在序列中。seq = [1, 2, 3] print(4 not in seq) # 输出 True
方法
- len(s)- 序列s中元素的个数。
- max(s)- 序列s中元素的最大值。
- min(s)- 序列s中元素的最小值。
- s.count(x)- 序列s中x出现的次数。
- seq.append(obj)- 在列表末尾添加新的对象。- seq = [1, 2, 3] seq.append(4) print(seq) # 输出 [1, 2, 3, 4]
- seq.clear()- 清空序列中的所有元素。- seq = [1, 2, 3] seq.clear() print(seq) # 输出 []
- seq.copy()- 返回序列的浅复制。- seq = [1, 2, 3] new_seq = seq.copy()
- seq.count(obj)- 统计序列中元素出现的次数。- seq = [1, 2, 2, 3] print(seq.count(2)) # 输出 2
- seq.extend(iterable)- 将可迭代对象中的所有元素追加到序列末尾。
seq = [1, 2, 3]
seq.extend([4, 5])
print(seq)  # 输出 [1, 2, 3, 4, 5]
- seq.index(obj)- 返回序列中第一个匹配元素的索引。
seq = [1, 2, 3]
print(seq.index(2))  # 输出 1
- seq.insert(index, obj)- 将对象插入到序列指定位置。
seq = [1, 2, 4]
seq.insert(2, 3)
print(seq)  # 输出 [1, 2, 3, 4]
- seq.pop([index])- 移除列表中的一个元素(默认最后一个元素),并返回该元素的值。
seq = [1, 2, 3]
print(seq.pop())  # 输出 3
- seq.remove(obj)- 移除序列中第一个匹配的元素。
seq = [1, 2, 3]
seq.remove(2)
print(seq)  # 输出 [1, 3]
- seq.reverse()- 反转序列中元素的顺序。- seq = [1, 2, 3] seq.reverse() print(seq) # 输出 [3, 2, 1]
- seq.sort(key=None, reverse=False)- 对序列中的元素进行排序。- seq = [3, 1, 2]
