使用内置功能构建

高效编写 Python 代码

Logan Thomas

Scientific Software Technical Trainer, Enthought

Python 标准库

  • Python 3.6 标准库
    • 每个标准 Python 安装都包含
  • 内置类型
    • listtuplesetdict
  • 内置函数
    • print()len()range()round()enumerate()map()zip()
  • 内置模块
    • ossysitertoolscollectionsmath
高效编写 Python 代码

内置函数:range()

显式输入一个数字列表

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
高效编写 Python 代码

使用 range() 创建相同列表

# range(start,stop)
nums = range(0,11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# range(stop)
nums = range(11)

nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
高效编写 Python 代码

内置函数:range()

range() 中使用步长

even_nums = range(2, 11, 2)

even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
高效编写 Python 代码

内置函数:enumerate()

创建带索引的对象列表

letters = ['a', 'b', 'c', 'd' ]

indexed_letters = enumerate(letters)

indexed_letters_list = list(indexed_letters)
print(indexed_letters_list)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
高效编写 Python 代码

内置函数:enumerate()

可指定起始值

letters = ['a', 'b', 'c', 'd' ]

indexed_letters2 = enumerate(letters, start=5)

indexed_letters2_list = list(indexed_letters2)
print(indexed_letters2_list)
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]
高效编写 Python 代码

内置函数:map()

对对象逐项应用函数

nums = [1.5, 2.3, 3.4, 4.6, 5.0]

rnd_nums = map(round, nums)

print(list(rnd_nums))
[2, 2, 3, 5, 5]
高效编写 Python 代码

内置函数:map()

map()lambda(匿名函数)配合使用

nums = [1, 2, 3, 4, 5]

sqrd_nums = map(lambda x: x ** 2, nums)

print(list(sqrd_nums))
[1, 4, 9, 16, 25]
高效编写 Python 代码

开始用内置功能构建吧!

高效编写 Python 代码

Preparing Video For Download...