增
nums = [1, 2, 3]
nums.append(4) # [1, 2, 3, 4] 末尾添加 1 个
nums.extend([5, 6]) # [1, 2, 3, 4, 5, 6] 末尾批量添加
nums.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6] 指定位置插入
nums + [7, 8] # 返回新列表,不改原列表
删
nums.remove(3) # 按值删除第一个 3,没有会 ValueError
nums.pop() # 弹出末尾,返回它
nums.pop(0) # 弹出指定位置
del nums[2] # 按下标删除
nums.clear() # 清空
改 / 查
nums[0] = 99 # 直接赋值
nums.index(99) # 查值返回下标,没有抛 ValueError
nums.count(2) # 出现次数
2 in nums # True / False(成员检查)
排序
nums.sort() # 原地升序
nums.sort(reverse=True) # 原地降序
nums.sort(key=abs) # 按绝对值排
sorted(nums) # 返回新列表,不改原列表
排字符串列表 / 字典列表都靠 key:
words = ["banana", "apple", "cherry"]
words.sort(key=len) # 按长度排:['apple', 'banana', 'cherry']
people = [{"name": "B", "age": 30}, {"name": "A", "age": 25}]
people.sort(key=lambda p: p["age"])
反转
nums.reverse() # 原地反转
nums[::-1] # 切片反转,返回新列表
切片高级技巧
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums[2:8:2] # [2, 4, 6] 每 2 个取 1 个
nums[::-2] # [9, 7, 5, 3, 1] 逆向每 2 个取 1 个
# 切片赋值(替换一段)
nums[2:5] = [100, 200] # [0, 1, 100, 200, 5, 6, 7, 8, 9]
# 复制列表(重要!)
copy = nums[:] # 切片是浅拷贝
copy = nums.copy() # 同上
下一篇讲元组 Tuple——和列表很像,但不可变。