处理列表 · Python 从零开始
怎样回答关于整个列表的问题:最大值、平均值、哪些符合条件?
课程目录为什么需要它
数据放进列表之后,真正的工作是向它提问。Python 自带了一些帮手(sum、max、min、sorted),你也可以用已经学会的套路自己写:循环 + 条件 + 累加器,或者循环 + 条件 + append 建一个新列表(筛选 Filtering)。
直觉理解
| 帮手 | 得到 |
|---|---|
sum(xs) | 总和 |
max(xs)、min(xs) | 最大值、最小值 |
len(xs) | 个数 |
sorted(xs) | 一个新的、排好序的列表 |
x in xs | x 在列表里就是 True |
平均值 = sum(xs) / len(xs)。
筛选就是「只留下通过检查的元素」:
passed = []
for s in scores:
if s >= 50:
passed.append(s)会自己写 max(记住目前最好的那个,遇到更好的就替换)是很经典的面试热身题。
定义
筛选 Filtering
Filtering builds a new list containing only the items of another list that satisfy a condition.筛选是建一个新列表,只放入原列表中满足条件的元素。
内置函数 Built-in function
A built-in function, such as sum, max or sorted, is always available in Python without importing anything.内置函数(如 sum、max、sorted)在 Python 里随时可用,不需要导入任何东西。
示例
气温报告
动手试试先用内置函数,再做筛选。
temps = [21, 25, 19, 30, 24]
print(max(temps), min(temps))
print(sum(temps) / len(temps))
hot = []
for t in temps:
if t >= 24:
hot.append(t)
print(hot)逐步执行
- L2最大值和最小值。
30 19 - L3平均值:119 / 5。
23.8 - L6逐个检查 t,只有 25、30、24 通过。
- L8筛选后的列表保持原来的顺序。
[25, 30, 24]
手写最大值
动手试试这就是 max() 内部用的思路。
words = ["cat", "elephant", "dog"]
longest = words[0]
for w in words:
if len(w) > len(longest):
longest = w
print(longest)
print(sorted(words))逐步执行
- L2目前最好的:第一个单词。
longest = 'cat' - L4elephant 比 cat 长:替换。
longest = 'elephant' - L4dog 不比它长:保留 elephant。
- L7sorted 按字母顺序排列,而且不改动 words。
['cat', 'dog', 'elephant']
常见错误
空列表的平均值
sum([]) / len([]) 会除以 0。先检查 if len(xs) > 0:。
sorted() 和 .sort()
sorted(xs) 返回新列表;xs.sort() 直接修改 xs,返回 None。不要写 xs = xs.sort()。
小测验
1. 这段代码会输出什么?
print(sorted([3, 1, 2])[0], max([3, 1, 2]))查看答案
答案:A
sorted 得到 [1, 2, 3],第一个是 1;最大值是 3。
2. 这段代码会输出什么?
a = [1, 2, 3, 4]
b = []
for x in a:
if x % 2 == 0:
b.append(x * 10)
print(b)查看答案
答案:A
只有偶数 2 和 4 通过,再各乘以 10。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出成绩单
准确写出程序的输出。
- 改需求更多统计
这段程序打印及格的分数。接着再打印两行:不及格(低于 50)的有几个,以及最高分。
- 从零写高于平均
读入 n,再读入 n 个整数。把严格大于平均值的数按原来的顺序放进一个列表并打印。
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| Filtering | 筛选 | Building a new list with only the items that pass a test. |
| Built-in function | 内置函数 | A function such as sum or max that Python provides without imports. |
| sorted() | sorted() 排序函数 | A built-in that returns a new list with the items in ascending order. |
| Average | 平均值 | The sum of the values divided by how many there are. |