Python容器类型差异操作

Python中提供了多种内置容器类型,用于存储和组织数据。其中最常用的是列表(list) 、字典(dict) 和集合(set),它们各有特点,适用于不同的场景。除此之外,Python标准库还提供了许多其他有用的容器类型,如元组、数组、双端队列等。下面我们将详细说明它们的差异、支持的操作,并给出代码示例。


一、列表、字典、集合的差异

类型 是否有序 是否可变 元素是否唯一 访问方式 典型用途
列表(list) 有序(插入顺序) 可变 可重复 整数索引 存储序列数据,支持增删改查
字典(dict) 有序(Python 3.7+) 可变 键唯一,值可重复 键(key) 存储键值对映射关系
集合(set) 无序 可变 唯一 无索引,只能遍历或成员测试 去重、集合运算(并交差)

示例

python 复制代码
# 列表
lst = [1, 2, 3, 2]        # 有序,允许重复
print(lst[0])              # 通过索引访问 → 1

# 字典
dct = {'a': 1, 'b': 2}     # 键值对,键唯一
print(dct['a'])            # 通过键访问 → 1

# 集合
st = {1, 2, 3, 2}          # 自动去重 → {1, 2, 3}
print(2 in st)             # 成员测试 → True

二、类似的其他容器类型

除了上述三种,Python还提供了以下常用容器(部分位于collections模块):

类型 特点 示例
元组(tuple) 有序、不可变、可重复 t = (1, 2, 3)
数组(array) 同类型元素,更节省内存 from array import array; a = array('i', [1, 2, 3])
双端队列(deque) 两端高效插入/弹出 from collections import deque; dq = deque([1, 2, 3])
命名元组(namedtuple) 类似元组,但字段可命名 from collections import namedtuple; Point = namedtuple('Point', ['x', 'y']); p = Point(1, 2)
有序字典(OrderedDict) 记住插入顺序(内置dict已有序,但OrderedDict提供额外方法) from collections import OrderedDict; od = OrderedDict()
默认字典(defaultdict) 访问不存在的键时返回默认值 from collections import defaultdict; dd = defaultdict(int)
计数器(Counter) 字典子类,用于计数 from collections import Counter; c = Counter('abracadabra')
链映射(ChainMap) 将多个字典逻辑合并为一个 from collections import ChainMap
用户列表/字典/字符串(UserList等) 方便继承并自定义行为 from collections import UserList

三、支持的操作详解(增删改查、运算及其他)

1. 列表(list)

  • 增 :append()、extend()、insert()、+(拼接)
  • 删 :remove()、pop()、del、clear()
  • 改 :直接索引赋值 lst[i] = new_value
  • 查 :索引访问、切片、in、index()、count()
  • 运算 :
    • +:拼接列表 [1,2] + [3,4] → [1,2,3,4]
    • *:重复列表 [1,2] * 3 → [1,2,1,2,1,2]
    • 比较:==、<(按字典序比较)
  • 其他 :len()、max()、min()、sorted()、列表推导式、reverse()、sort()、copy()等
python 复制代码
lst = [1, 2]
lst.append(3)          # [1,2,3]
lst.insert(1, 99)      # [1,99,2,3]
lst.remove(2)          # [1,99,3]
popped = lst.pop()     # popped=3, lst=[1,99]
lst[0] = 100           # [100,99]
print(100 in lst)      # True
print(lst + [5,6])     # [100,99,5,6]
print(lst * 2)         # [100,99,100,99]

2. 字典(dict)

  • 增/改 :d[key] = value、update()、setdefault()
  • 删 :del d[key]、pop(key)、popitem()、clear()
  • 查 :d[key](键不存在会报错)、get(key, default)、in、keys()、values()、items()
  • 运算 :
    • Python 3.9+:| 合并字典 {1:'a'} | {2:'b'} → {1:'a', 2:'b'}
    • |= 更新字典
  • 其他 :len()、字典推导式、copy()、fromkeys()等
python 复制代码
d = {'a': 1, 'b': 2}
d['c'] = 3             # 增 → {'a':1, 'b':2, 'c':3}
d['a'] = 100           # 改 → {'a':100, 'b':2, 'c':3}
del d['b']             # 删 → {'a':100, 'c':3}
print(d.get('x', 0))   # 查(不存在返回0)→ 0
print('a' in d)        # True
print(d.keys())        # dict_keys(['a', 'c'])
# 合并(Python 3.9+)
d2 = d | {'d': 4}      # {'a':100, 'c':3, 'd':4}

3. 集合(set)

  • 增 :add()、update()(可添加多个)
  • 删 :remove()(元素不存在报错)、discard()(不报错)、pop()(随机弹出一个)、clear()
  • 查 :in、isdisjoint()、issubset()等
  • 运算 :
    • | 并集 {1,2} | {2,3} → {1,2,3}
    • & 交集 {1,2} & {2,3} → {2}
    • - 差集 {1,2} - {2,3} → {1}
    • ^ 对称差集 {1,2} ^ {2,3} → {1,3}
    • 比较:<=、<、>=、> 判断子集/超集
  • 其他 :len()、集合推导式、copy()等
python 复制代码
s = {1, 2, 3}
s.add(4)               # {1,2,3,4}
s.discard(2)           # {1,3,4}
s.remove(3)            # {1,4}
print(1 in s)          # True
print(s | {5,6})       # {1,4,5,6}
print(s & {4,5,6})     # {4}
print(s - {4})         # {1}

4. 其他类型的常用操作

  • 元组(tuple) :不可变,所以没有增删改,但支持查(索引、切片、in)、拼接(+)、重复(*)、比较、len()等。

    python 复制代码
    t = (1, 2, 3)
    print(t[1])           # 2
    print(t + (4,))       # (1,2,3,4)
  • 数组(array) :支持类似列表的操作,但元素类型相同。提供append()、extend()、索引赋值等。

  • 双端队列(deque) :两端快速操作,append()、appendleft()、pop()、popleft()、rotate()等。

  • 默认字典(defaultdict) :当键不存在时自动调用工厂函数生成默认值。

    python 复制代码
    from collections import defaultdict
    dd = defaultdict(list)
    dd['a'].append(1)     # 即使键'a'不存在也会自动创建空列表
  • 计数器(Counter) :类似字典,用于计数,支持most_common()、加减运算(+、-)等。

    python 复制代码
    from collections import Counter
    c = Counter('abbccc')
    print(c)              # Counter({'c':3, 'b':2, 'a':1})
    print(c.most_common(2)) # [('c',3), ('b',2)]

四、总结:操作对比表

操作类别 列表 字典 集合 元组 备注
增 append, insert, extend d[key]=value, update add, update 不可变 字典的"增"同时也是"改"
删 remove, pop, del del, pop, popitem remove, discard, pop 不可变
改 索引赋值 键赋值 不可改元素 不可变 集合元素不可变,但可增删
查 索引、切片、in 键、get、in in、子集判断 索引、切片、in
运算 +(拼接), *(重复) ` `(合并, 3.9+) ` (并), &(交), -(差), ^`(对称差)
其他 sort, reverse, 推导式 推导式, keys, values 推导式, 去重 拆包, 命名元组扩展

通过以上对比,你可以根据具体需求选择合适的容器类型,并灵活运用它们提供的丰富操作。Python的容器生态非常强大,熟练掌握它们能极大提升编程效率。

相关推荐
yeflx1 分钟前
万向节死锁
python
亿道电子Emdoor3 分钟前
【Perforce】Klocwork-kwgcheck图形化界面无法打开如何解决
git·python·github
迅猛龙办公室2 小时前
python实现倒序输出数字
开发语言·python
全栈练习生11 小时前
AI Agent 沙箱
python·ai
SEO_juper13 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户83562907805114 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__14 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户83562907805114 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_4617694014 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
2601_9669496515 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash