Python3 内置函数

The 30 builtins that replace hand-written loops, with what each one actually does.

Beginner
Key PointsLearn `any`/`all`/`zip`/`enumerate`/`sorted(key=)`/`sum(generator)` — they replace most manual loops and read better.

Iteration Helpers

FunctionDoesExample
enumerate(it, start)Index + item pairslist(enumerate('ab', 1))
zip(a, b)Pair up, stops at shortestlist(zip([1,2], 'ab'))
map(f, it)Lazy transformlist(map(str, [1,2]))
filter(f, it)Keep where f is truthylist(filter(None, [0,1,2]))
reversed(seq)Reverse iterationlist(reversed([1,2,3]))
range(a, b, s)Numeric sequencelist(range(0, 10, 3))

Aggregation

FunctionDoesNote
sum(it, start=0)Add numbersWorks on generators
min / max(it, key=)Extremeskey= compares a projection
any(it)True if any truthyShort-circuits
all(it)True if all truthyEmpty -> True
len / abs / roundBasicsround uses banker's rounding
sorted(it, key=, reverse=)New sorted listStable sort
Python
nums = [3, 1, 4, 1, 5]

print(sum(nums), max(nums), min(nums))
print(any(n > 4 for n in nums), all(n > 0 for n in nums))   # True True
print(sorted(nums, reverse=True)[:2])                        # [5, 4]

# 找最大值的对象(而不是最大值本身)
rows = [{"n": "a", "v": 3}, {"n": "b", "v": 9}]
print(max(rows, key=lambda r: r["v"])["n"])                  # b

Type and Object Helpers

FunctionDoes
isinstance(x, T)Type check, supports tuples of types
type(x)Exact type object
hasattr / getattr / setattrDynamic attribute access
id(x)Identity (memory address)
repr(x) / str(x)Debug text / display text
hash(x)Hash value, needs __hash__
callable(x)Is it callable
iter / nextManual iteration
Python
isinstance(True, int)          # True —— bool 是 int 的子类
getattr(obj, "name", "n/a")    # 带默认值,属性缺失不报错

it = iter([1, 2])
next(it), next(it, None)       # (1, 2)

Functional Building Blocks

Python
from functools import reduce

reduce(lambda a, b: a * b, [1, 2, 3, 4])     # 24
list(map(lambda x: x * 2, [1, 2, 3]))         # [2, 4, 6]

# 推导式通常比 map/filter 更 Pythonic
[x * 2 for x in [1, 2, 3]]
map/filter return lazy iterators, not lists. Printing them shows <map object at 0x...> — wrap in list() when you need to inspect.

Friends & Partners