函数使用(四)

前言

  • 这一篇讲三块内容:能被 for-in 遍历的东西分几类(可迭代对象与迭代器)、iter 函数,以及 map / reduce / filter / sorted 这几个常用高级函数,最后收尾到模块与包。
  • 笔记是 2019 年记的,里面 from collections import Iterable 这类写法从 Python 3.3 起就该走 collections.abc,3.10 起直接 ImportError,本文已全部改成新写法,并在对应位置标注旧写法错在哪。
  • 所有示例都在 Python 3.13.9 上实跑,输出原样贴在代码块下面。

迭代器(Iterator)

  • 定义: 能用 next() 一个一个往下取元素的对象,也就是实现了 __next__ 的对象。取完之后再取会抛 StopIteration,for-in 就是靠捕获这个异常来结束循环的。

  • 两个抽象基类各自的要求(collections.abc 里):

    抽象基类 唯一抽象方法 含义
    Iterable __iter__ 能交出一个迭代器,for-in 认它
    Iterator __next__ 能逐个吐值,取完抛 StopIteration

    Iterator 是 Iterable 的子类(实测 issubclass(Iterator, Iterable) 为 True),所以迭代器一定可迭代,可迭代对象却不一定是迭代器。自己写迭代器时通常让 __iter__ 直接返回自身(return self),这样 for 拿到的就是它自己;返回另一个迭代器也合法,真正被遍历的是那个返回的对象。

  • 判断方式:

    1
    2
    3
    4
    from collections.abc import Iterator

    g = (i for i in range(10))
    print(isinstance(g, Iterator)) # True

    早期笔记里写的是 from collections import Iterator,Python 3.10 起这行直接报错:ImportError: cannot import name 'Iterator' from 'collections'。这些抽象基类从 3.3 起就搬到 collections.abc 了,旧位置只是保留了一段时间的别名。

  • 生成器是一种特殊的迭代器: issubclass(types.GeneratorType, Iterator) 实测为 True,迭代器却未必是生成器(map、zip 都不是)。

  • 谁是谁(本机 3.13.9 实测):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    from collections.abc import Iterable, Iterator

    # 一次性看清:可迭代 vs 是迭代器
    samples = {
    # 前六种都是「可迭代但不是迭代器」
    'list': [1, 2, 3],
    'str': 'ab',
    'tuple': (1, 2),
    'set': {1},
    'dict': {'a': 1},
    'range': range(3),
    # 从这行往后都是迭代器
    '生成器': (i for i in range(3)),
    'map': map(abs, [-1]),
    'filter': filter(None, [0, 1]),
    'zip': zip([1], [2]),
    'enumerate': enumerate('ab'),
    'reversed': reversed([1]),
    'iter(列表)': iter([1]),
    }
    # !s 把布尔转成字符串,好把输出对齐
    for name, obj in samples.items():
    print(f'{name:10} 可迭代={isinstance(obj, Iterable)!s:5} 迭代器={isinstance(obj, Iterator)}')

    输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    list       可迭代=True  迭代器=False
    str 可迭代=True 迭代器=False
    tuple 可迭代=True 迭代器=False
    set 可迭代=True 迭代器=False
    dict 可迭代=True 迭代器=False
    range 可迭代=True 迭代器=False
    生成器 可迭代=True 迭代器=True
    map 可迭代=True 迭代器=True
    filter 可迭代=True 迭代器=True
    zip 可迭代=True 迭代器=True
    enumerate 可迭代=True 迭代器=True
    reversed 可迭代=True 迭代器=True
    iter(列表) 可迭代=True 迭代器=True

    一句话记法:字符串、列表、元组、集合、字典、range 都只是可迭代对象;生成器和 map / filter / zip / enumerate / reversed / 文件对象 / iter() 的返回值才是迭代器。

  • next 的两种写法: 单参数取完就抛异常,带默认值就不抛。

    1
    2
    3
    4
    5
    6
    7
    8
    it = iter([1])
    print(next(it)) # 1
    print(next(it, '没了')) # 没了 —— 有默认值,不抛异常
    print(next(it, '没了')) # 没了 —— 可以反复取
    try:
    next(it)
    except StopIteration as e:
    print('单参数取完抛 StopIteration,value =', repr(e.value))

    输出:

    1
    2
    3
    4
    1
    没了
    没了
    单参数取完抛 StopIteration,value = None
  • 迭代器只能走一遍:

    1
    2
    3
    4
    5
    6
    7
    g = (i for i in range(3))
    # list() 会把它一口气取空
    print('第一遍:', list(g))
    print('第二遍:', list(g))
    nums = [1, 2, 3]
    # 可迭代对象每次都能重新要一个迭代器
    print('列表可以反复:', list(iter(nums)) == list(iter(nums)))

    输出:

    1
    2
    3
    第一遍: [0, 1, 2]
    第二遍: []
    列表可以反复: True

    这也是把「可迭代对象」当参数传进函数时最容易踩的坑:传进来的是迭代器的话,用第二次就是空的。

    1
    2
    3
    4
    5
    6
    7
    8
    # 参数收到迭代器时,函数内部只能用一遍
    def total(it):
    return sum(it)

    g = (i for i in range(3))
    # 第一次 sum 就把它耗光了
    print('传生成器: 第一次', total(g), '第二次', total(g))
    print('传列表: ', total([1, 2, 3]), total([1, 2, 3]))

    输出:

    1
    2
    传生成器: 第一次 3 第二次 0
    传列表: 6 6
  • 自己写一个迭代器: __iter__ 返回自身、__next__ 吐值并在结束时抛 StopIteration。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    from collections.abc import Iterator

    class Counter:
    def __init__(self, n):
    self.n = n
    self.i = 0

    def __iter__(self):
    return self # 迭代器必须把自己交出去

    def __next__(self):
    self.i += 1
    if self.i > self.n:
    raise StopIteration
    return self.i

    c = Counter(3)
    print(isinstance(c, Iterator), list(c), list(c))

    输出:

    1
    True [1, 2, 3] []
  • 整体示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    from collections.abc import Iterable, Iterator
    from types import GeneratorType

    # 1) 判断:迭代器一定可迭代,可迭代对象未必是迭代器
    lst, gen = [1, 2, 3], (i for i in range(3))
    print('列表 可迭代:', isinstance(lst, Iterable), ' 是迭代器:', isinstance(lst, Iterator))
    print('生成器 可迭代:', isinstance(gen, Iterable), ' 是迭代器:', isinstance(gen, Iterator))
    print('生成器是迭代器的子类:', issubclass(GeneratorType, Iterator))
    print('Iterator 是 Iterable 的子类:', issubclass(Iterator, Iterable))

    # 2) next:单参数会抛 StopIteration,带默认值不会
    it = iter(lst)
    print('next(it):', next(it))
    print('带默认值:', next(it, '空了'), next(it, '空了'), next(it, '空了'))

    # 3) 迭代器一次性的本质:把它当参数传进函数,第二次就取不到了
    def twice(x):
    first, second = list(x), list(x)
    return first, second

    print('传迭代器:', twice(iter('ab')))
    print('传列表:', twice([1, 2]))

    实跑输出:

    1
    2
    3
    4
    5
    6
    7
    8
    列表 可迭代: True  是迭代器: False
    生成器 可迭代: True 是迭代器: True
    生成器是迭代器的子类: True
    Iterator 是 Iterable 的子类: True
    next(it): 1
    带默认值: 2 3 空了
    传迭代器: (['a', 'b'], [])
    传列表: ([1, 2], [1, 2])

可迭代对象(Iterable)

  • 定义: 能用 for-in 遍历的对象,统称可迭代对象。正式标准是实现了 __iter__;此外还有一条历史兜底——只实现 __getitem__、且能从 0 开始连续按下标取(越界抛 IndexError)的对象,for 与 iter() 照样能用,但 isinstance(x, Iterable) 仍然是 False,见下面的实测。

  • 判断方式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    from collections.abc import Iterable

    l = [1, 2, 3]
    lt = (1, 2, 3)
    s = 'abc'
    d = {'a': 1}
    # 容器和字符串都实现了 __iter__
    for x in (l, lt, s, d):
    print(type(x).__name__, isinstance(x, Iterable))
    # 数字没有 __iter__,for 也走不动
    print('数字不可迭代:', isinstance(123, Iterable))

    输出:

    1
    2
    3
    4
    5
    list True
    tuple True
    str True
    dict True
    数字不可迭代: False

    早期笔记里这段写的是 from collections import Iterable,Python 3.10 起同样 ImportError

  • 可迭代对象 ≠ 迭代器: 它自己不能被 next,因为 for 每次都会重新 iter() 要一个新的迭代器,所以能反复遍历。

    1
    2
    3
    4
    5
    6
    s = 'ab'
    print([c for c in s], [c for c in s]) # 列表反复遍历没问题
    try:
    next(s)
    except TypeError as e:
    print('next(字符串):', e)

    输出:

    1
    2
    ['a', 'b'] ['a', 'b']
    next(字符串): 'str' object is not an iterator
  • 只实现 __getitem__ 的对象(老式序列协议): 实测 for、iter() 都能走,isinstance 两种基类却都是 False,next() 也不能直接对它用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    from collections.abc import Iterable, Iterator

    class OnlyGetItem:
    def __init__(self, data):
    self.data = data

    def __getitem__(self, i):
    return self.data[i] # 越界抛 IndexError,for 靠它结束

    o = OnlyGetItem([10, 20, 30])
    print('for 能走:', [x for x in o])
    print('iter() 也能走:', iter(o) is not None)
    print('isinstance Iterable / Iterator:', isinstance(o, Iterable), isinstance(o, Iterator))
    try:
    next(o)
    except TypeError as e:
    print('next(它):', e)

    输出:

    1
    2
    3
    4
    for 能走: [10, 20, 30]
    iter() 也能走: True
    isinstance Iterable / Iterator: False False
    next(它): 'OnlyGetItem' object is not an iterator
  • 自己写一个可迭代对象: 只要 __iter__ 交出一个迭代器即可,不必自己实现 __next__。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from collections.abc import Iterable, Iterator

    class Repeat:
    def __init__(self, obj, times):
    self.obj = obj
    self.times = times

    def __iter__(self):
    return iter([self.obj] * self.times) # 交给列表的迭代器

    r = Repeat('x', 3)
    print('可迭代:', isinstance(r, Iterable), ' 是迭代器:', isinstance(r, Iterator))
    print('for 遍历:', [x for x in r], ' 再来一次:', list(r))

    输出:

    1
    2
    可迭代: True  是迭代器: False
    for 遍历: ['x', 'x', 'x'] 再来一次: ['x', 'x', 'x']
  • 整体示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    from collections.abc import Iterable, Iterator

    # 1) 常见可迭代对象:六种容器 + range + 字符串
    for x in ([1], (1,), {1}, {'a': 1}, 'a', range(2)):
    print(type(x).__name__, '可迭代', isinstance(x, Iterable), '迭代器', isinstance(x, Iterator))

    # 2) 字典遍历默认拿 key;values / items 也是可迭代对象
    d = {'b': 2, 'a': 1}
    print('默认:', list(d), 'values:', list(d.values()), 'items:', list(d.items()))

    # 3) 可迭代对象可以反复遍历,这一点和迭代器相反
    lst = [1, 2]
    print('两次遍历:', list(lst) == list(lst))
    print('sum 直接吃可迭代对象:', sum(range(5)))
    print('生成器表达式也能直接吃:', sum(i * i for i in range(4)))

    实跑输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    list 可迭代 True 迭代器 False
    tuple 可迭代 True 迭代器 False
    set 可迭代 True 迭代器 False
    dict 可迭代 True 迭代器 False
    str 可迭代 True 迭代器 False
    range 可迭代 True 迭代器 False
    默认: ['b', 'a'] values: [2, 1] items: [('b', 2), ('a', 1)]
    两次遍历: True
    sum 直接吃可迭代对象: 10
    生成器表达式也能直接吃: 14

iter 函数

  • 作用: 把可迭代对象换成迭代器(for 循环内部做的第一件事就是它)。

  • 用法一:iter(可迭代对象)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    from collections.abc import Iterator

    lt = (1, 2, 3)
    # 元组 -> tuple_iterator
    it = iter(lt)
    print(type(it).__name__, isinstance(it, Iterator))
    # 一次吐一个
    print(next(it), next(it), next(it))
    print('对迭代器再 iter() 得到它自己:', iter(it) is it)
    try:
    # 不可迭代的对象直接 TypeError
    iter(123)
    except TypeError as e:
    # 不可迭代的对象直接 TypeError
    print('iter(123):', e)

    输出:

    1
    2
    3
    4
    tuple_iterator True
    1 2 3
    对迭代器再 iter() 得到它自己: True
    iter(123): 'int' object is not iterable
  • 用法二:iter(函数, 哨兵值) —— 反复调用无参数函数,直到返回值等于哨兵值才停,哨兵那个值本身不会出现在结果里。读文件、读设备这类「不知道有多少条」的场景很好用。

    1
    2
    3
    4
    5
    6
    7
    import io

    counter = iter(range(1, 6))
    print(list(iter(lambda: next(counter), 4))) # [1, 2, 3],取到 4 就停,4 不要

    buf = io.StringIO('第一行\n第二行\n')
    print(list(iter(buf.readline, ''))) # 读到空字符串为止

    输出:

    1
    2
    [1, 2, 3]
    ['第一行\n', '第二行\n']
  • for 循环的等价拆解: 下面两段完全等价,看懂了迭代器就通了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 写法 A:平时用的 for-in
    for i in [10, 20, 30]:
    print(i)

    # 写法 B:手工展开 for 做的事
    it = iter([10, 20, 30]) # 1) 先拿迭代器
    while True:
    try:
    x = next(it) # 2) 不停 next
    except StopIteration: # 3) 取完自动结束
    break
    print(x)

    输出(两段各打一遍,共 6 行):

    1
    2
    3
    4
    5
    6
    10
    20
    30
    10
    20
    30
  • 练习:

    1
    2
    1. 用 iter + next(不用 for)把一个字符串逐个打印出来
    2. 用 iter(函数, 哨兵) 写一个「输入 q 结束」的循环
  • 整体示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    # 1) 单个参数:可迭代对象 -> 迭代器
    it = iter('hi')
    print('类型:', type(it).__name__, '逐个取:', next(it), next(it))

    # 2) for 的等价展开
    total = 0
    nums = iter([1, 2, 3])
    while True:
    try:
    total += next(nums)
    except StopIteration:
    break
    print('手工累加:', total)

    # 3) 两个参数:反复调用直到撞上哨兵
    lines = iter(['a', 'b', 'q', 'c'])
    print('取到 q 为止:', list(iter(lambda: next(lines), 'q')), '剩下的:', list(lines))

    # 4) 迭代器可以传给任何吃可迭代对象的函数(但只有一次机会)
    print('sum(迭代器):', sum(iter([1, 2, 3])))

    实跑输出:

    1
    2
    3
    4
    类型: str_ascii_iterator 逐个取: h i
    手工累加: 6
    取到 q 为止: ['a', 'b'] 剩下的: ['c']
    sum(迭代器): 6

高级函数

高级函数指「函数能当参数传、或者返回值还能当输入用」这一类函数。Python 里 map、filter、sorted 是内置函数,reduce 在 functools 里。

  • map

    • 格式: map(func, 可迭代对象, ...)

    • 说明: 把 func 依次作用于每个元素,返回一个 map 迭代器(不是生成器,实测 isinstance(map(...), GeneratorType) 为 False)。它是惰性的:创建时一个都不算,取的时候才算,所以也只能遍历一遍。传多个可迭代对象时以最短的那个为准。

    • 示例:

      1
      2
      3
      4
      5
      6
      7
      l = [1, 2, 3, 4, 5]
      print(map(lambda x: x * 2, l)) # <map object at 0x...>
      print(list(map(lambda x: x * 2, l))) # [2, 4, 6, 8, 10]
      print(list(map(lambda x: x * x, l))) # [1, 4, 9, 16, 25]
      print(list(map(abs, [-1, -2, 3]))) # [1, 2, 3] 具名函数比 lambda 更省事
      print(list(map(lambda a, b: a + b, [1, 2], [10, 20, 30]))) # 以最短为准
      print(list(map(str, [1, 2]))) # ['1', '2']

      输出:

      1
      2
      3
      4
      5
      6
      <map object at 0x0000016924545570>
      [2, 4, 6, 8, 10]
      [1, 4, 9, 16, 25]
      [1, 2, 3]
      [11, 22]
      ['1', '2']

      地址每次运行都不一样,看个大概就行。Python 2 里 map(None, ... 能用 None 占位的写法在 Python 3 已经没了,实测 map(None, [1, 2]) 抛 TypeError: 'NoneType' object is not callable,要并列就用 zip。

    • 惰性验证:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      calls = []

      def rec(x):
      calls.append(x)
      return x * 2

      # 创建时一个都不算
      m = map(rec, [1, 2, 3])
      print('创建后:', calls)
      # 取到哪个才算哪个
      print('取一个:', next(m), calls)
      print('剩下的:', list(m), calls)

      输出:

      1
      2
      3
      创建后: []
      取一个: 2 [1]
      剩下的: [4, 6] [1, 2, 3]
    • 练习: 处理一个元素为字符串的列表,要求把字符串两端的空白去掉,然后首字母大写。(str.strip 与 str.capitalize 组合,见下面整体示例的写法)

  • reduce

    • 格式: reduce(func, 可迭代对象[, initial]),在 functools 里,必须显式导入。

    • 说明: 先取前两个元素交给 func,结果再和第三个元素继续算,一路归约成一个值返回。第三个参数 initial 是起始值(只能按位置传,实测写成 initial=10 会抛 TypeError: reduce() takes no keyword arguments)。序列为空又没给 initial 时抛 TypeError;序列只有一个元素时直接返回该元素,func 一次都不执行。

    • 示例:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      from functools import reduce

      l = [1, 2, 3, 4, 5]
      print(reduce(lambda x, y: x + y, l)) # 15 求和
      print(reduce(lambda x, y: x * 10 + y, l)) # 12345 数字列表拼成一个整数
      print(reduce(lambda x, y: x + y, l, 100)) # 115 带 initial
      print(reduce(lambda x, y: x + y, [], 0)) # 0 空序列 + initial
      print(reduce(lambda x, y: x + y, [7])) # 7 单元素直接返回
      print(reduce(lambda a, b: a + b, ['py', 'thon']))
      try:
      reduce(lambda x, y: x + y, [])
      except TypeError as e:
      print('空序列没给 initial:', e)

      输出:

      1
      2
      3
      4
      5
      6
      7
      15
      12345
      115
      0
      7
      python
      空序列没给 initial: reduce() of empty iterable with no initial value

      求和求积这类事有内置的 sum、math.prod,比 reduce 快也更 readable;reduce 留给「归约规则是自己定的」场景。

    • 练习: 求列表中所有元素的乘积。(reduce(lambda x, y: x * y, l, 1,或者用 math.prod)

  • filter

    • 格式: filter(func, 可迭代对象)

    • 说明: func 依次作用于每个元素,保留结果为真值的,返回 filter 迭代器(同样是惰性的,也只能遍历一遍)。func 传 None 时相当于「保留所有真值」,正好用来剔除空字符串、0、None 这些。

    • 示例:

      1
      2
      3
      4
      5
      l = [1, 2, 3, 4, 5]
      print(filter(lambda x: x % 2 == 0, l))
      print(list(filter(lambda x: x % 2 == 0, l))) # 偶数 [2, 4]
      print(list(filter(None, [0, 1, '', 'a', None, [], [2]]))) # func=None:只留真值
      print(list(filter(str.isalpha, ['a', '1', 'b']))) # 传具名方法也可以

      输出:

      1
      2
      3
      4
      <filter object at 0x0000027D5BD45600>
      [2, 4]
      [1, 'a', [2]]
      ['a', 'b']
    • 练习: 提取既为奇数又能被 3 整除的元素。

  • sorted

    • 说明:

      • 对任意可迭代对象排序,返回一个新列表,原对象不动;默认升序。
      • key 传一个函数,指定「拿什么比」。不传 key 就直接拿元素本身比:数字比大小,字符串则逐字符比 Unicode 码点(跟查字典的字母顺序一样,所以常叫「字典序」/「lexicographic」)——
        所以大写字母排在所有小写字母前面,中文也不是按拼音排,见下面示例。
      • reverse=True 改成降序。注意它不是「把升序结果整个倒过来」:Python 的排序是稳定的,key 相同的元素之间仍保持原顺序,实测 sorted([(1, 'a'), (1, 'b'), (1, 'c')], key=lambda t: t[0], reverse=True) 仍是 a, b, c 的顺序,真要整体倒序用 reversed(sorted(...))。
      • 与 list.sort() 的区别:后者原地排序、返回 None,只有列表能用。
    • 示例:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      l = [
      {'name': 'xiaowang', 'age': 18, 'height': 150},
      {'name': 'xiaogang', 'age': 20, 'height': 140},
      {'name': 'xiaohong', 'age': 19, 'height': 145},
      ]
      # 按 age 降序
      print([(d['name'], d['age']) for d in sorted(l, key=lambda x: x['age'], reverse=True)])
      # 多关键字:age 降序、age 相同再按 height 升序(数值取负是最省事的写法)
      print([(d['age'], d['height']) for d in sorted(l, key=lambda x: (-x['age'], x['height']))])
      # 字符串按长度排;长度相同再逐字符比('ant' < 'bee')
      print(sorted(['bee', 'ant', 'cow', 'bee2'], key=lambda w: (len(w), w)))
      # 不传 key 时字符串就是逐字符比码点:大写在小写前面
      print(sorted(['banana', 'Apple', 'apple']))
      # 中文按码点排,不是拼音顺序(按拼音该是 北京 < 上海 < 西安)
      print(sorted(['北京', '上海', '西安']))
      # 什么都能排:字典默认排 key,排 value 要先 items()
      print(sorted({'b': 1, 'a': 2}), sorted({'b': 1, 'a': 2}.items(), key=lambda kv: kv[1]))
      print(sorted({3, 1}), sorted('python'))
      # list.sort 原地排、返回 None
      tmp = [3, 1, 2]
      print('sort 的返回值:', tmp.sort(), ' 排完的列表:', tmp)

      输出:

      1
      2
      3
      4
      5
      6
      7
      8
      [('xiaogang', 20), ('xiaohong', 19), ('xiaowang', 18)]
      [(20, 140), (19, 145), (18, 150)]
      ['ant', 'bee', 'cow', 'bee2']
      ['Apple', 'apple', 'banana']
      ['上海', '北京', '西安']
      ['a', 'b'] [('b', 1), ('a', 2)]
      [1, 3] ['h', 'n', 'o', 'p', 't', 'y']
      sort 的返回值: None 排完的列表: [1, 2, 3]

      sorted 要求元素之间可比,混着 int 和 str 会抛 TypeError,这时候一律用 key 把它们换算成同一种可比的值。

  • 整体示例(map / reduce / filter / sorted 全用上)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    from functools import reduce

    words = [' apple ', 'Banana', 'cherry', ' apple ', '', 'date']

    # 1) map:清理 + 统一小写(这就是上面那道练习题)
    cleaned = list(map(lambda w: w.strip().lower(), words))
    print('map 清理后:', cleaned)

    # 2) filter:把空字符串剔掉(func 传 None 就是「只留真值」)
    not_empty = list(filter(None, cleaned))
    print('filter 去空:', not_empty)

    # 3) reduce:拼成一个字符串,并数一下总字符数
    joined = reduce(lambda a, b: a + '/' + b, not_empty)
    print('reduce 拼接:', joined)
    print('reduce 数长度:', reduce(lambda n, w: n + len(w), not_empty, 0))

    # 4) sorted:按长度升序;长度相同的再逐字符比('apple' < 'banana')
    print('按长度排序:', sorted(not_empty, key=lambda w: (len(w), w)))
    print('降序且原列表不动:', sorted(not_empty, reverse=True), not_empty)

    # 5) 四个串起来:先清洗、再过滤、再排序、最后归约成一行输出
    line = reduce(lambda a, b: a + ' | ' + b,
    sorted(filter(None, map(lambda w: w.strip().lower(), words)), key=len))
    print('串起来:', line)

    实跑输出:

    1
    2
    3
    4
    5
    6
    7
    map 清理后: ['apple', 'banana', 'cherry', 'apple', '', 'date']
    filter 去空: ['apple', 'banana', 'cherry', 'apple', 'date']
    reduce 拼接: apple/banana/cherry/apple/date
    reduce 数长度: 26
    按长度排序: ['date', 'apple', 'apple', 'banana', 'cherry']
    降序且原列表不动: ['date', 'cherry', 'banana', 'apple', 'apple'] ['apple', 'banana', 'cherry', 'apple', 'date']
    串起来: date | apple | apple | banana | cherry

模块使用

  • 定义

    模块就像一个工具包,里面装着别人(或你自己)写好的函数、类、变量,用 import 拿进来就能用。一个 .py 文件就是一个模块。

  • 分类

    • 标准库:随 Python 装好,如 random、sys、os、time
    • 第三方:前人写好、用 pip 安装的包
    • 自定义:自己写的 .py 文件
  • 导入的四种写法

    1
    2
    3
    4
    import random                 # 导入,用的时候写 random.xxx
    import random as rdm # 导入并起别名
    from time import sleep # 指定导入,直接用 sleep
    from time import sleep as sp # 指定导入并起别名

    起别名之后,原来的名字就不存在了:import random as rdm 之后写 random.randint(1, 6) 会抛 NameError,只能用 rdm。

  • 星号导入(模糊导入)

    1
    2
    # 只导入 __all__ 里点名的名字
    from random import *
    • 模块里定义了 __all__ 列表时,只导入列表里点名的那些名字;没定义时,导入所有不以下划线开头的名字。实测 random、os、functools 这些标准库都自带 __all__。
    • 下划线开头的名字(_b)永远进不来,这是 Python 的「私有」约定。
    • 正式代码里不建议用:读代码的人不知道 a() 是哪来的,也容易和当前文件的名字撞车。
    1
    2
    3
    # no_star.py:def a() / def _b() / c = ... / __all__ = ['a', 'c']
    from no_star import *
    print(sorted(n for n in dir() if not n.startswith('__')))

    输出:

    1
    ['a', 'c']
  • 自定义模块

    • 新建一个 .py 文件,文件名不和其他模块同名即可;文件名(去掉后缀)就是模块名。
    • 导入方式和标准库完全相同,前提是解释器能在搜索路径里找到它(一般就是和入口脚本放同一目录)。
    • 文件名(模块名)就是一个命名空间,不同命名空间里的同名标识符互不干扰。
    • 多个模块里有同名函数时,用「模块名限定」或「起别名」解决:
      1
      2
      3
      4
      5
      6
      7
      8
      import random
      import zidingyi

      print(random.randint(1, 10)) # 用模块名限定

      from random import randint as r_rint
      from zidingyi import randint as z_rint
      print(r_rint(1, 10), z_rint(1, 10)) # 或者各起一个别名
  • 测试模块(__name__)

    • 模块作为主程序运行时 __name__ 是 '__main__';被别的模块导入时是模块名。
    • 所以模块底部的自测代码普遍这样写,导入它时不会被执行:
      1
      2
      3
      4
      5
      6
      # zidingyi.py 里
      def randint(a, b):
      return a

      if __name__ == '__main__': # 只有直接运行 zidingyi.py 时才打印
      print('测试代码')
      1
      2
      3
      4
      import zidingyi

      # 被 import 时 __name__ 就是模块名
      print('被导入时 __name__ =', zidingyi.__name__)
      输出:
      1
      被导入时 __name__ = zidingyi
  • 包(package)

    • 定义: 多个模块放在同一目录下,目录里有一个 __init__.py,这个目录就是一个包;包里还能有子目录(子包)。
    • __init__.py 的作用: 导入包时它先执行,在里面做 re-export 就能简化外面的写法(from sound_pkg import set_volume 而不是 from sound_pkg.volume import set_volume);它还能用 __all__ 限制星号导入的内容。
    • 目录里没有 __init__.py 也能导入吗?Python 3.3 起可以,那种叫命名空间包(实测能 import 成功,但它的 __spec__.origin 是 None,也没有 __init__.py 可以做初始化)。自己写项目时建议老老实实放一个 __init__.py,行为可控、工具识别得好。
    • 包内部互相引用用相对导入(from .volume import set_volume,一个点代表当前包)。
  • 安装第三方模块

    • 工具是 pip。建议一律写成 python -m pip,能保证「给当前这个解释器装包」,避免机器上装了多个 Python 时装错地方。
    • 常用命令:
      1
      2
      3
      4
      5
      6
      7
      python -m pip install 包名            # 安装(自动装依赖)
      python -m pip install -U 包名 # 升级
      python -m pip uninstall 包名 # 卸载
      python -m pip list # 列出已安装的包
      python -m pip show 包名 # 看某个包的详情(版本、位置、依赖)
      python -m pip freeze # 按 requirements.txt 的格式输出
      python -m pip config list # 看当前配置
    • 国内镜像(2026-11 本机实测可用):
      1
      2
      3
      清华     https://pypi.tuna.tsinghua.edu.cn/simple
      阿里云 https://mirrors.aliyun.com/pypi/simple/
      中国科大 https://pypi.mirrors.ustc.edu.cn/simple/

      老笔记里还抄着华中理工大学 pypi.hustunique.com、山东理工大学 pypi.sdutlinux.org、豆瓣 pypi.douban.com 三个源,实测分别返回 301 后连接失败、410 Gone、域名解析失败,早就不能用了;阿里云也要用 https,写 http 会被重定向甚至报证书错。

    • 临时用一次镜像,加 -i 就行,不必改配置:
      1
      python -m pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
    • 永久改源,推荐直接用 pip config,它会自动写到正确位置:
      1
      python -m pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
      等价于手写配置文件。Windows 上用户级配置是 %APPDATA%\pip\pip.ini(本机 python -m pip config debug 实测还会顺带认 C:\Users\你\pip\pip.ini),Linux/macOS 是 ~/.config/pip/pip.conf。文件内容:
      1
      2
      3
      [global]
      index-url = https://pypi.tuna.tsinghua.edu.cn/simple
      trusted-host = pypi.tuna.tsinghua.edu.cn
    • 注意: 装不上通常是三类原因——网络或源不可用、公司/代理证书拦截、没有写权限(这时用 python -m pip install --user 包名 装到用户目录)。
  • 整体示例(自定义模块 + 包 + 命名空间)

    目录结构(入口脚本和各模块同级放,解释器才找得到):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    fn4_demo/
    main.py
    no_star.py
    zidingyi.py
    sound_pkg/
    __init__.py
    volume.py
    effects/
    __init__.py
    echo.py
    zidingyi.py
    1
    2
    3
    4
    5
    6
    7
    8
    import random

    def randint(a, b):
    """与 random.randint 重名,用来演示命名空间互不干扰"""
    return random.randint(a, b) + 1000 # 故意 +1000 以便区分

    def only_here():
    return '只在 zidingyi 里有'

    sound_pkg/__init__.py(re-export,简化外面的写法):

    1
    2
    3
    4
    from .volume import set_volume            # 相对导入:同一个包内的模块
    from .effects.echo import echo

    __all__ = ['set_volume', 'echo']

    sound_pkg/effects/echo.py:

    1
    2
    def echo(text, times=2):
    return ' '.join([text] * times)

    main.py:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import random         # 标准库
    import zidingyi # 自定义模块
    import random as rdm # 起别名
    from zidingyi import randint as z_rint
    from no_star import * # 星号导入:只拿 __all__ 里点名的
    import sound_pkg # 导入包 = 先执行它的 __init__.py
    from sound_pkg.effects.echo import echo as e2 # 深层模块 + 别名

    random.seed(0)
    print('random.randint:', random.randint(1, 10))
    print('zidingyi.randint:', zidingyi.randint(1, 10)) # 模块名限定,重名不打架
    print('别名导入后:', rdm.choice(['甲', '乙']))
    print('两个 randint 各自独立:', z_rint(1, 10) != random.randint(1, 10))
    print('只能通过模块名拿到的:', zidingyi.only_here())
    print('星号导入:', a(), '|', c, '| _b 没进来:', '_b' not in dir())
    print('包 __init__ 里 re-export:', sound_pkg.set_volume(8))
    print('子包模块:', sound_pkg.echo('喂'))
    print('深层导入起别名:', e2('回音', 3))
    print('__name__ 在主模块里是:', __name__)

    python main.py 实跑输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    random.randint: 7
    zidingyi.randint: 1007
    别名导入后: 甲
    两个 randint 各自独立: True
    只能通过模块名拿到的: 只在 zidingyi 里有
    星号导入: a() 被星号导入带进来了 | c 是模块级变量 | _b 没进来: True
    包 __init__ 里 re-export: 音量调到 8
    子包模块: 喂 喂
    深层导入起别名: 回音 回音 回音
    __name__ 在主模块里是: __main__

参考

本文结束 感谢您的阅读
正在加载今日诗词....