PYTHON MINI PROJECTS / APPENDIX B

附录 B · 内置函数速查表APPENDIX B · 用的时候回来翻

目标:按用途记住"有这个函数",用的时候再查参数。下面每个函数都在前面章节敲过。

按用途分组类型 / 数学序列 / 迭代对象 / 反射

本章内容与知识点

附录 B 是一张内置函数速查表,按用途分组:输入输出、类型、数学、序列、迭代、真假判断、对象与反射。目标不是背参数,而是看到需求能想到有这个函数、用时再查。表里每个函数都在前面章节敲过。 用法:先通读表格挑出没印象的,再做任务按需求去表里选函数。

基础
输入输出类型查看 / 转换
运算
数学真假判断
序列迭代
序列与迭代函数式工具
对象
对象与反射其他常用
案例

速查表 + 分类检索(跟着敲)

介绍 · 一张表看全
分类函数一句话记忆
输入输出print / input / open输出、读一行、打开文件
类型查看type / isinstance / id看类型、判断是否、看身份
类型转换int / float / str / bool / list / dict / set / tuple把一种东西变成另一种
数学abs / round / max / min / sum / pow / divmod绝对值、四舍五入、最值、求和、幂、商余
序列与迭代len / range / enumerate / zip / reversed / sorted长度、造序列、带序号、配对、反转、排序
真假判断all / any / bool全真、有真、转真假
函数式map / filter逐个变形、按条件筛选
对象与反射dir / help / getattr / setattr / hasattr / callable查属性、查文档、动态操作
其他常用super / hash / repr / format / vars父类、哈希、表示、格式化、属性字典

写一个 builtin_index.py,把这些名字存成字典并做"按分类查询":

# -*- coding: utf-8 -*-
"""附录 B 速览:按用途把内置函数用一遍。"""
import keyword

idx = {"数学": ["abs", "round", "max", "min", "sum"],
       "序列": ["len", "range", "sorted", "zip"]}
for k, v in idx.items(): print("分类:", k, len(v), v)
print("关键字:", keyword.iskeyword("if"), keyword.issoftkeyword("match"))
print("转换:", int("3"), float("1.5"), str(2), bool(0))
print("序列:", list(range(3)), list(enumerate("ab")), sorted([2, 1]))
print("判断:", any([0, 1]), all([1, 2]), len("abc"))
print("函数式:", list(map(str, [1, 2])), list(filter(lambda x: x % 2 == 0, [1, 2])))
分类: 数学 5 ['abs', 'round', 'max', 'min', 'sum']
分类: 序列 4 ['len', 'range', 'sorted', 'zip']
关键字: True True
转换: 3 1.5 2 False
序列: [0, 1, 2] [(0, 'a'), (1, 'b')] [1, 2]
判断: True True 3
函数式: ['1', '2'] [2]
任务 1

速查表挑战:按需求选函数

自己敲 · 10 道小题
解题提示:本题主要用到 10 道小题、输入输出、类型查看。先对照要求自己敲一遍,卡住了再展开答案。

写 challenge.py,每道题用一个内置函数,直接写出结果并打印:

  1. 求字符串 "Python" 的长度。
  2. 把 "42" 变成整数再加 8。
  3. 判断 3.5 是不是 int。
  4. 求 [2,9,4] 的最大值、最小值、总和。
  5. 生成 0~4 的列表。
  6. 给 ["a","b"] 加序号,打印元组列表。
  7. 把 [1,2] 和 ["x","y"] 配成元组列表。
  8. 把 [3,1,2] 排序。
  9. 判断 [0,1,2] 里有没有真值。
  10. 把 [1,2,3] 每个元素乘 10(用 map)。
我的代码草稿
参考答案(先自己敲,再看)
# challenge.py —— 内置函数挑战
print("1:", len("Python"))
print("2:", int("42") + 8)
print("3:", isinstance(3.5, int))
nums = [2, 9, 4]
print("4:", max(nums), min(nums), sum(nums))
print("5:", list(range(5)))
print("6:", list(enumerate(["a", "b"])))
print("7:", list(zip([1, 2], ["x", "y"])))
print("8:", sorted([3, 1, 2]))
print("9:", any([0, 1, 2]))
print("10:", list(map(lambda x: x * 10, [1, 2, 3])))
1: 6
2: 50
3: False
4: 9 2 15
5: [0, 1, 2, 3, 4]
6: [(0, 'a'), (1, 'b')]
7: [(1, 'x'), (2, 'y')]
8: [1, 2, 3]
9: True
10: [10, 20, 30]
任务 2

查文档训练:不靠背也能用

自己敲 · dir / help / __doc__
解题提示:本题主要用到 dir、help、__doc__。先对照要求自己敲一遍,卡住了再展开答案。

写 explore.py,目标是"现场学会一个没用过的函数":

  • 用 dir(str) 找出所有含 case 的方法并打印。
  • 用 help(str.zfill) 看文档(可能你的版本有),再用 "7".zfill(3) 验证。
  • 打印 sum.__doc__ 的前 80 个字符。
  • 用 hasattr(str, "zfill") 和 getattr(str, "zfill") 各试一次。
  • 注释写下你这次"查到了什么",形成自己的笔记。
我的代码草稿
参考答案(先自己敲,再看)
# explore.py —— 现场查文档
print("str 里含 case 的方法:", [x for x in dir(str) if "case" in x])

print("zfill 存在吗:", hasattr(str, "zfill"))
print("取到的方法对象:", getattr(str, "zfill"))
print("验证 zfill:", "7".zfill(3))

print("sum 的文档前 80 字:", sum.__doc__[:80])

help(str.zfill)
str 里含 case 的方法: ['casefold', 'swapcase']
zfill 存在吗: True
取到的方法对象: <method 'zfill' of 'str' objects>
验证 zfill: 007
sum 的文档前 80 字: Return the sum of a 'start' value (default: 0) plus an
(help 会打印一段更完整的说明)

以后遇到没见过的函数,就按这个顺序:先 dir() 找名字,再 help() 看用法,最后写一行代码验证。

任务 3

round的银行家舍入

自己敲 · round / 内置坑
解题提示:本题主要用到 round、浮点精度、内置函数。先对照要求自己敲一遍,卡住了再展开答案。

发现 round 在 .5 时的"奇葩"行为。

  • 打印 round(2.5) 和 round(3.5)。
  • 你会看到结果是 2 和 4——这叫"银行家舍入",取最近的偶数。
  • 打印 round(2.675, 2),观察它也不是 2.68(浮点表示问题)。
  • 思考:需要精确舍入时该用什么(decimal)。
提示:Python 3 的 round 用"四舍六入五成双",和小学数学的"四舍五入"不完全一样。
我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己敲,再看)
# round 的银行家舍入
print("round(2.5) =", round(2.5))
print("round(3.5) =", round(3.5))
print("round(2.675, 2) =", round(2.675, 2))
print("round(1.25, 1) =", round(1.25, 1))
round(2.5) = 2
round(3.5) = 4
round(2.675, 2) = 2.67
round(1.25, 1) = 1.2
任务 4

any与all的空列表

自己敲 · any / all / 真假值
解题提示:本题主要用到 any、all、真假值。先对照要求自己敲一遍,卡住了再展开答案。

两个高频坑:any 和 all 遇到空列表时的返回值。

  • 打印 any([]) 和 all([]),记住结果是 False 和 True。
  • 打印 any([0, 0, 1])(有一个真即为真)。
  • 打印 all([1, 2, 3])(全真才为真)。
  • 用 all() 检查一串数是否都大于 0。
提示:all([]) 返回 True 是数学上的"空真"约定,容易踩坑,牢记。
我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己敲,再看)
# any 与 all 的空列表
print("any([]) =", any([]))
print("all([]) =", all([]))
print("any([0,0,1]) =", any([0, 0, 1]))
print("all([1,2,3]) =", all([1, 2, 3]))
print("都大于0:", all(x > 0 for x in [3, 5, 7]))
any([]) = False
all([]) = True
any([0,0,1]) = True
all([1,2,3]) = True
都大于0: True
任务 5

查文档:用help和__doc__

自己敲 · help / __doc__ / dir
解题提示:本题主要用到 help、__doc__、dir。先对照要求自己敲一遍,卡住了再展开答案。

不靠背,用工具查清 str.upper 的用法并打印文档字符串。

  • 打印 str.upper.__doc__ 的前 60 个字符。
  • 用 [m for m in dir(str) if 'case' in m] 找出所有含 case 的方法名。
  • 验证 "abc".upper() 的结果是 "ABC"。
提示:__doc__ 是对象的文档字符串;dir() 列出可用名字,配合过滤能快速定位方法。
我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己敲,再看)
# 查文档:help 和 __doc__
print(str.upper.__doc__[:60])
print("含 case 的方法:", [m for m in dir(str) if "case" in m])
print("'abc'.upper() =", "abc".upper())
Return a copy of the string converted to uppercase.
含 case 的方法: ['casefold', 'swapcase']
'abc'.upper() = ABC

附:完整内置函数分组清单(快速扫一眼)

输入输出:print input open
类型相关:type isinstance issubclass id hash repr format vars
数值转换:int float complex bool str bytes bytearray list tuple dict set frozenset
数学:abs round max min sum pow divmod
迭代序列:len range enumerate zip reversed sorted iter next filter map
聚合判断:all any
对象操作:getattr setattr delattr hasattr dir help super callable object classmethod staticmethod property
作用域:globals locals vars exec eval compile
其他:__import__ breakpoint input memoryview slice bin oct hex chr ord ascii