Python 3.1 新特性全面总结

Python 3.1 新特性全面总结

发布时间:2009 年 6 月 27 日

官方文档:https://docs.python.org/zh-cn/3.1/whatsnew/3.1.html


一、新语法特性

1. 自动编号字段 {}

python 复制代码
# 3.1+:自动按顺序编号,无需手动写 {0} {1}
'Sir {} of {}'.format('Gallahad', 'Camelot')
# 等价于
'Sir {0} of {1}'.format('Gallahad', 'Camelot')

2. 多上下文管理器

python 复制代码
# 3.1+:单个 with 语句多个管理器,无需嵌套
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
    for line in infile:
        outfile.write(line)

# contextlib.nested() 废弃(不再需要)

3. round() 返回整数类型

python 复制代码
# 3.1+:round(整数, n) 返回 int
round(1123, -2)  # 1100(int,而非 float)

二、新增标准库

collections.OrderedDict --- 有序字典(PEP 372)

python 复制代码
from collections import OrderedDict

# 记住插入顺序
d = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1)])
list(d)  # ['banana', 'apple', 'pear']

# 排序字典:按键排序
OrderedDict(sorted(d.items(), key=lambda t: t[0]))

# 排序字典:按值排序
OrderedDict(sorted(d.items(), key=lambda t: t[1]))

# 排序后删除再添加,新键追加到末尾,不维持排序

注:Python 3.7+ 普通 dict 也保证插入顺序,但 OrderedDict 仍有 move_to_end()、相等比较考虑顺序等独特功能。

collections.Counter --- 计数器

python 复制代码
from collections import Counter

Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
# Counter({'blue': 3, 'red': 2, 'green': 1})

c = Counter(a=2, b=1, c=0, d=-2)
# 常用操作
+c       # Counter({'a': 2, 'b': 1})  移除计数 ≤ 0 的元素
-c       # Counter({'d': 2})          负数变正数
c.most_common(3)  # 最常见的 3 个元素
c.elements()      # 迭代器

tkinter.ttk --- 主题部件集

python 复制代码
from tkinter import ttk

# 分离外观和行为,Tk 主题部件集
style = ttk.Style()
style.theme_use('clam')
ttk.Button(root, text='Click').pack()

importlib --- 导入系统纯 Python 参考实现

python 复制代码
import importlib

# 提供 import 语句的纯 Python 实现
# 完整、可移植,定义了导入期间的所有行为
importlib.import_module('my_package.my_module')

logging.NullHandler --- 空日志处理器

python 复制代码
import logging

# 库代码使用,抑制 "No handlers could be found" 警告
h = logging.NullHandler()
logging.getLogger('mylib').addHandler(h)

三、格式化改进

千分位分隔符(PEP 378)

python 复制代码
format(1234567, ',d')          # '1,234,567'
format(1234567.89, ',.2f')     # '1,234,567.89'
format(1234567.89, ',f')       # '1,234,567.890000'
format(12345.6 + 8901234.12j, ',f')  # '12,345.6+8,901,234.12j'

浮点数 repr() 改进

python 复制代码
# 3.0:repr(1.1) 返回冗长的 '1.1000000000000001'
# 3.1+:自动寻找最短等价表示 '1.1'
repr(1.1)   # '1.1'(更简洁,值不变)
format(1.1, '.17g')  # '1.1000000000000001'(旧算法仍可访问)

四、标准库重要改进

1. int.bit_length() --- 位数计算

python 复制代码
>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6

>>> (2**123 - 1).bit_length()
123

2. itertools 新增函数

python 复制代码
# 组合(含重复)
>>> from itertools import combinations_with_replacement
>>> list(combinations_with_replacement('LOVE', 2))
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']

# compress:按选择器过滤, 0 不要, 1 保留
>>> from itertools import compress
>>> list(compress(range(10), [0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]

# count 支持 step 参数和任意序列
>>> from itertools import count
>>> c = count(start=0.5, step=0.25)
>>> [next(c) for _ in range(5)]
[0.5, 0.75, 1.0, 1.25, 1.5]

3. unittest 增强

python 复制代码
class Tests(unittest.TestCase):

    @unittest.skipUnless(sys.platform.startswith('win'), 'requires Windows')
    def test_windows_feature(self): ...

    @unittest.expectedFailure
    def test_known_bug(self): ...

    # assertRaises 作为上下文管理器
    def test_division_by_zero(self):
        with self.assertRaises(ZeroDivisionError):
            x / 0

    # 新增大量断言方法
    self.assertSetEqual(set1, set2)
    self.assertDictEqual(d1, d2)
    self.assertListEqual(l1, l2)
    self.assertSequenceEqual(s1, s2)
    self.assertIsNone(obj)
    self.assertIsNotNone(obj)

4. namedtuple rename 参数

python 复制代码
from collections import namedtuple

# rename=True:自动将无效字段名改为 _0, _1 ...
# 用于外部数据源(CSV/SQL/用户输入)
UserQuery = namedtuple('UserQuery',
    ['region', 'dept', 'count(*)'],  # 'count(*)' 无效
    rename=True)
# UserQuery._fields = ('region', 'dept', '_2')

5. 其他改进

python 复制代码
# gzip / bz2 支持上下文管理器
with gzip.GzipFile(filename, 'wb') as f:
    f.write(b'data')

# Decimal.from_float() 精确转换
Decimal.from_float(1.1)
# Decimal('1.100000000000000088817841970012523233890533447265625')

# re.sub/re.split/re.subn 接受 flags 参数
re.sub(r'\d+', str, text, flags=re.IGNORECASE)

# functools.partial 可 pickle
import pickle
pickle.dumps(functools.partial(func, arg))

# sys.version_info 是 named tuple
sys.version_info.major  # 3
sys.version_info.minor  # 1

# io 新增常量
io.SEEK_SET  # 0
io.SEEK_CUR  # 1
io.SEEK_END  # 2

# pickle 协议 2 自动处理 Python 2/3 兼容
pickle.dumps(s, protocol=2, fix_imports=True)  # 自动映射 builtin -> builtins

# string.maketrans() 废弃
# 3.1+: bytes.maketrans() / bytearray.maketrans() / str.maketrans()

# runpy 支持包执行
# python -m mypackage 查找 __main__ 子模块

五、性能优化

优化 效果
I/O 库 C 重写 提速 2-20 倍
--with-computed-goto 字节码分发提速 20%
UTF-8/16/LATIN-1 解码 提速 2-4 倍
GC 启发式 减少垃圾收集开销
JSON C 扩展 大幅提速
unpickle 属性名 intern 减少内存占用
整数存储 30 位进制 64 位机器性能大幅提升
python 复制代码
# sys.int_info 显示整数内部格式
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
# 64 位:30 位/数字;32 位:15 位/数字

总结

Python 3.1 的核心亮点:

  1. OrderedDict --- 有序字典,记住插入顺序
  2. 千分位分隔符 , --- format(1234567, ',d')'1,234,567'
  3. int.bit_length() --- 所需二进制位数
  4. 自动编号字段 {} --- format() 简化
  5. 多上下文管理器 --- with A() as a, B() as b: 无需嵌套
  6. Counter --- 便捷计数
  7. 浮点数 repr() 改进 --- 显示更简洁
  8. itertools 新函数 --- combinations_with_replacementcompress
  9. unittest.skip/expectedFailure --- 测试跳过和预期失败
  10. I/O 库 C 重写 --- 性能提升 2-20 倍

Python 3.1 是一个性能大幅提升 + 实用工具增加 的版本。Python 3.0 的 I/O 库性能问题在 3.1 中得到彻底解决(C 重写),同时 OrderedDictCounter 等新工具让常见编程模式更简洁。浮点数 repr() 的改进也解决了 3.0 时代用户最常抱怨的 "1.1 为什么显示成 1.1000000000000001" 问题。


参考:Python 3.1 官方文档 - What's New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。

相关推荐
贫民窟的勇敢爷们1 小时前
构建基于Python与机器学习的智能客服
开发语言·python·机器学习
shehuiyuelaiyuehao1 小时前
算法20,x的平方根
开发语言·python·算法
AI精钢1 小时前
AI 正在重构所有 App:要么消失,要么原生于智能体框架之上
人工智能·python·云原生·重构·aigc
测试员周周1 小时前
【AI测试数据及模型质量2】换一批测试数据,模型得分差20%——AI评测翻车的根子,90%在数据质量
人工智能·python·ui·单元测试·测试用例·集成测试·pytest
神仙别闹1 小时前
基于Python实现一个C语言的编译器
java·c语言·python
yivifu1 小时前
使用PyMuPDF基于对PDF文档内容的分析自动识别并删除PDF文件中的水印
python·pdf·pymupdf·去水印
Allen_LVyingbo1 小时前
面向医疗群体智能的协同诊疗与群体决策支持系统(下)
开发语言·数据结构·windows·python·动态规划
于先生吖1 小时前
家政派单小程序源头开发厂家
python
SunnyDays10111 小时前
如何使用 Python 删除 Word 文档空白行(含批量处理)
python·删除word文档空白行