目录
各项容器独有 py容器List py容器Dict py容器Str py容器Set py容器Tuple
一、通用内置函数 len max/min sum 除dict、str count 仅有序容器(list, tuple, str) index 仅有序容器(list, tuple, str) 成员判断
三、通用排序 sorted 返回排序后的新列表 reversed 返回反转后的迭代器
四、通用迭代 enumerate 返回索引和值 除dict zip
五、序列切片 仅有序容器(list, tuple, str)
注意事项
| 容器类型 | 是否有序 | 是否可变 | 是否允许重复 |
|---|---|---|---|
| list | ✅ | ✅ | ✅ |
| tuple | ✅ | ❌ | ✅ |
| str | ✅ | ❌ | ✅ |
| set | ❌ | ✅ | ❌ |
| dict | ✅ (Python3.7+) | ✅ | 键唯一、值重复 |
常用操作速查
| 操作 | list | tuple | str | set | dict |
|---|---|---|---|---|---|
索引访问 [i] | ✅ | ✅ | ✅ | ❌ | ❌ |
切片 [i:j] | ✅ | ✅ | ✅ | ❌ | ❌ |
| 修改元素 | ✅ | ❌ | ❌ | ❌ | ✅ |
| 添加元素 | append() | ❌ | ❌ | add() | [key]=value |
| 删除元素 | remove() | ❌ | ❌ | remove() | pop(key) |
| 成员判断 | in | in | in | in | in(键) |
性能对比
# 查找元素速度(快→慢)
# 1. set / dict (O(1))
# 2. list (O(n))
# 3. tuple (O(n))
# 适用场景:
# - 需要快速查找:用 set 或 dict
# - 需要顺序和可修改:用 list
# - 需要顺序且不可变:用 tuple
# - 需要键值对映射:用 dict
# - 需要去重:用 set通用操作
案例
py容器案例
Python 容器案例
下面这段代码可以直接复制到
.py文件中运行,覆盖list、tuple、dict、set、str的常见操作,以及浅拷贝和深拷贝区别。指向原始笔记的链接 import copy from functools import reduce def list_case(): students = ["Tom", "Lucy", "Jack"] students.append("Lily") students.insert(1, "Bob") print("list add:", students) removed = students.pop() students.remove("Bob") print("list remove:", removed, students) scores = [80, 95, 72, 88] print("list sorted copy:", sorted(scores)) scores.sort(reverse=True) print("list in-place sort:", scores) print("list comprehension:", [score for score in scores if score >= 80]) def tuple_case(): user = ("Tom", 20, "Beijing") name, age, city = user print("tuple unpack:", name, age, city) print("tuple count:", (1, 2, 2, 3).count(2)) def dict_case(): profile = {"name": "Tom", "age": 20} profile["city"] = "Beijing" profile.update({"score": 95}) print("dict:", profile) print("dict get:", profile.get("name"), profile.get("missing", "default")) for key, value in profile.items(): print("dict item:", key, value) defaults = {"role": "student", "score": 0} print("dict merge:", defaults | profile) def set_case(): a = {1, 2, 3} b = {3, 4, 5} print("set union:", a | b) print("set intersection:", a & b) print("set difference:", a - b) print("set comprehension:", {x * x for x in range(10) if x % 2 == 0}) def str_case(): text = " Python,Java,Go " cleaned = text.strip() print("str cleaned:", cleaned) print("str split:", cleaned.split(",")) print("str join:", " | ".join(cleaned.split(","))) print("str f-string:", f"{'Tom'} score={95.678:.2f}") def common_case(): numbers = [3, 1, 4, 1, 5] print("len/max/min/sum:", len(numbers), max(numbers), min(numbers), sum(numbers)) print("sorted/reversed:", sorted(numbers), list(reversed(numbers))) print("map:", list(map(lambda x: x * 2, numbers))) print("filter:", list(filter(lambda x: x % 2 == 1, numbers))) print("reduce:", reduce(lambda a, b: a + b, numbers)) def copy_case(): students = [["Tom", 80], ["Lucy", 95]] shallow = students.copy() shallow[0][1] = 100 print("after shallow copy:", students) students = [["Tom", 80], ["Lucy", 95]] deep = copy.deepcopy(students) deep[0][1] = 100 print("after deep copy:", students) print("deep copy:", deep) def main(): list_case() tuple_case() dict_case() set_case() str_case() common_case() copy_case() if __name__ == "__main__": main()
一、通用内置函数
len
len(容器) - 返回容器中元素个数
mylist = [1, 2, 3, 4]
mystr = "1234"
mytuple = (1, 2, 3, 4)
myset = {1, 2, 3, 4}
mydict = {"key1":1, "key2":2, "key3":3, "key4":4}
print(len(mylist)) # 4
print(len(mystr)) # 4
print(len(mytuple)) # 4
print(len(myset)) # 4
print(len(mydict)) # 4max/min
max(容器) - 返回最大元素值
min(容器) - 返回最小元素值
mylist = [1, 2, 3, 4]
mystr = "1234"
mytuple = (1, 2, 3, 4)
myset = {1, 2, 3, 4}
mydict = {"key1":1, "key2":2, "key3":3, "key4":4}
print(max(mylist)) # 4
print(max(mystr)) # '4' (字符串按ASCII比较)
print(max(mytuple)) # 4
print(max(myset)) # 4
print(max(mydict)) # 'key4' (字典比较的是键)
print(min(mylist)) # 1
print(min(mystr)) # '1'
print(min(mytuple)) # 1
print(min(myset)) # 1
print(min(mydict)) # 'key1'sum
sum(容器) - 返回所有元素的和(只适用于数值类型)
mylist = [1, 2, 3, 4]
mytuple = (1, 2, 3, 4)
myset = {1, 2, 3, 4}
print(sum(mylist)) # 10
print(sum(mytuple)) # 10
print(sum(myset)) # 10
# 字符串和字典不能求和count
count(元素) - 统计元素出现次数
mylist = [1, 2, 2, 3, 2, 4]
mystr = "hello"
mytuple = (1, 2, 2, 3, 2, 4)
print(mylist.count(2)) # 3
print(mystr.count('l')) # 2
print(mytuple.count(2)) # 3
# set 和 dict 没有 count() 方法index
index(元素) - 查找元素首次出现的位置
mylist = [1, 2, 3, 2, 4]
mystr = "hello"
mytuple = (1, 2, 3, 2, 4)
print(mylist.index(2)) # 1
print(mystr.index('l')) # 2
print(mytuple.index(2)) # 1
# set 和 dict 没有 index() 方法(无序)成员判断
元素 in 容器 - 判断元素是否存在
元素 not in 容器 - 判断元素是否不存在
if判断同理
mylist = [1, 2, 3, 4]
mystr = "1234"
mytuple = (1, 2, 3, 4)
myset = {1, 2, 3, 4}
mydict = {"key1":1, "key2":2}
print(2 in mylist) # True
print('2' in mystr) # True (字符串检查子串)
print(2 in mytuple) # True
print(2 in myset) # True
print('key1' in mydict) # True (字典检查键)
print(1 in mydict) # False (检查的是键,不是值)二、容器类型转换
转list
mylist = [1, 2, 3, 4]
mystr = "1234"
mytuple = (1, 2, 3, 4)
myset = {1, 2, 3, 4}
mydict = {"key1":1, "key2":2, "key3":3, "key4":4}
print(list(mylist)) # [1, 2, 3, 4]
print(list(mystr)) # ['1', '2', '3', '4']
print(list(mytuple)) # [1, 2, 3, 4]
print(list(myset)) # [1, 2, 3, 4]
print(list(mydict)) # ['key1', 'key2', 'key3', 'key4'] (取键)转tuple
print(tuple(mylist)) # (1, 2, 3, 4)
print(tuple(mystr)) # ('1', '2', '3', '4')
print(tuple(mytuple)) # (1, 2, 3, 4)
print(tuple(myset)) # (1, 2, 3, 4)
print(tuple(mydict)) # ('key1', 'key2', 'key3', 'key4')转str
print(str(mylist)) # "[1, 2, 3, 4]"
print(str(mystr)) # "1234"
print(str(mytuple)) # "(1, 2, 3, 4)"
print(str(myset)) # "{1, 2, 3, 4}"
print(str(mydict)) # "{'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4}"转set
print(set(mylist)) # {1, 2, 3, 4}
print(set(mystr)) # {'1', '2', '3', '4'} (顺序随机)
print(set(mytuple)) # {1, 2, 3, 4}
print(set(myset)) # {1, 2, 3, 4}
print(set(mydict)) # {'key1', 'key2', 'key3', 'key4'} (取键,顺序随机)三、通用排序
sorted
返回排序后的新列表,注意返回的是全新的列表List
sorted(容器, reverse=False) - 正序
sorted(容器, reverse=True) - 倒序
mylist = [3, 1, 4, 2]
mystr = "3142"
mytuple = (3, 1, 4, 2)
myset = {3, 1, 4, 2}
mydict = {"key3":3, "key1":1, "key4":4, "key2":2}
# 正序
print(sorted(mylist)) # [1, 2, 3, 4]
print(sorted(mystr)) # ['1', '2', '3', '4']
print(sorted(mytuple)) # [1, 2, 3, 4]
print(sorted(myset)) # [1, 2, 3, 4]
print(sorted(mydict)) # ['key1', 'key2', 'key3', 'key4'] (按键排序)
# 倒序
print(sorted(mylist, reverse=True)) # [4, 3, 2, 1]
print(sorted(mystr, reverse=True)) # ['4', '3', '2', '1']reversed
返回反转后的迭代器
reversed(容器) - 倒序
mylist = [1, 2, 3, 4]
print(list(reversed(mylist))) # [4, 3, 2, 1]
mystr = "1234"
print(''.join(reversed(mystr))) # "4321"四、通用迭代
enumerate
for 索引, 值 in enumerate(容器): - 返回索引和值的迭代器
mylist = ['a', 'b', 'c']
for i, value in enumerate(mylist):
print(i, value)
# 0 a
# 1 b
# 2 czip
zip(容器1, 容器2, ...) - 并行迭代多个容器,返回元组迭代器
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 85
# Bob: 92
# Charlie: 78五、序列切片
序列:有序支持索引的数据集
序列[起始下标:结束下标:步长]
表示从指定序列开始,依次取出元素,到指定位置(不包含)结束,得到一个新序列:
- 起始下标可留空,留空视作从头开始
- 结束下标可留空,视作到序列尾结束
- 步长表示,依次取得的元素间隔
- 不写(默认)为1
- 步长为N表示跳过N-1个元素取
- 步长为负数表示反向取(起始下标和结束下标也要互换)
# 例一
list1 = [0, 1, 2, 3, 4, 5, 6]
print(list[1:4]) # output:[1, 2, 3]
# 例二
tuple1 = (0, 1, 2, 3, 4, 5, 6)
print(tuple1[:]) # output:(0, 1, 2, 3, 4, 5, 6)
# 例三
string = "01234567"
print(string[::2]) #output:0246
# 例四
string2 = "01234567"
print(string[::-1]) # output:76543210
# 例五
list2 = [0, 1, 2, 3, 4, 5, 6]
print(list2[3:1:-1]) #output:[3, 2]
# 例六
tuple2 = (0, 1, 2, 3, 4, 5, 6)
print(tuple2[::-2]) #output:(6, 4, 2, 0)# 例子:
string = "万过薪月,员序程马黑来,nohtyp学"
print(string[::-1][9:14])
print(string[5:11][::-1])
print(string[10:4:-1])
# alloutput:来黑马程序员六、迭代相关
all
所有元素都为 True 返回 True
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(all([1, 2, 3])) # True (非0为True)
print(all([1, 0, 3])) # False
# 应用:检查所有括号是否匹配完
stack = []
# all(not stack) 等价于检查栈是否为空any
任一元素为 True 返回 True
print(any([False, False, True])) # True
print(any([False, False, False])) # False
print(any([0, 0, 1])) # True七、高级操作
map
对每个元素应用函数
mylist = [1, 2, 3, 4]
result = list(map(lambda x: x * 2, mylist))
print(result) # [2, 4, 6, 8]
mystr = "1234"
result = ''.join(map(lambda x: chr(ord(x)+1), mystr))
print(result) # "2345"filter
过滤元素
mylist = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, mylist))
print(result) # [2, 4, 6]
# 过滤空值
values = [0, 1, False, 2, '', 3, None, 4]
result = list(filter(None, values))
print(result) # [1, 2, 3, 4]reduce
累积计算(需导入functools)
from functools import reduce
mylist = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, mylist)
print(result) # 10
result = reduce(lambda x, y: x * y, mylist)
print(result) # 24八、特有但可类比的方法
虽然不属于其他容器方法,但思路类似:
join
字符串.join(任意容器) - 连接(字符串专用,但可用于所有容器)返回字符串
separator = ","
print(separator.join(['a', 'b', 'c'])) # list: "a,b,c"
print(separator.join(('a', 'b', 'c'))) # tuple: "a,b,c"
print(separator.join("abc")) # str: "a,b,c"
print(separator.join({'a', 'b', 'c'})) # set: 顺序随机
print(separator.join({'a':1, 'b':2, 'c':3})) # dict: 连接的是键 "a,b,c"九、解包操作
* 解包(列表、元组、字符串)
# 列表解包
mylist = [1, 2, 3]
a, b, c = mylist
print(a, b, c) # 1 2 3
# 扩展解包
a, *b = [1, 2, 3, 4]
print(a) # 1
print(b) # [2, 3, 4]
# 字符串解包
a, b, c = "123"
print(a, b, c) # 1 2 3** 解包(字典)
def func(a, b, c):
print(a, b, c)
mydict = {"a": 1, "b": 2, "c": 3}
func(**mydict) # 1 2 3
# 合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}