标题不知道是翻译成“理解数据”呢,还是“推导数据”,反正不影响学习...因为Head First系列可能一小个知识点弄了好几页,所以感觉有做笔记必要,容易复习。这章主要还是前面几章的应用。发现一个没提到的return
表达式,代码中加括号不加括号貌似没区别,书中加括号反而感觉不能适应。
5. Comprehending(推导) Data: Work that Data!
Sort in one of two ways
使用Python对数据排序时,有两种选择:
In-place sorting(原地排序) —— 转换然后替换 —— sort()
BIF
Copied sorting(复制排序) —— 转换然后返回 —— sorted()
BIF
默认升序排序(ascending order). 要降序排序(descending order),向sort()
或sorted()
传入reverse=True
参数。
Comprehending lists 推导列表
Consider what you need to do when you transform one list into another. Four things have to happen. You need to:
- Create a new list to hold the transformed data.
- Iterate each data item in the original list.
- With each iteration, perform the transformation.
- Append the transformed data to the new list.
例如,mikey是一个现有list,要把mikey中的元素经过sanitizer函数加工后,放入clean_mikey中,如下:
列表推导 list comprehension,代替上面迭代方法
分钟转成秒:
Iterate to remove duplicates
list是允许重复的,要删除list中重复元素,可以进行遍历,然后删除重复的如下:
要访问一个列表中的多个数据项,可以使用分片(list slice)。如取出0到3(不包括3)的元素,my_list[0:3]
。
Remove duplicates with sets
“集合”——一组无序的数据项,其中不包含重复项。
Create an empty set using the set()
BIF, which is an example of a factory function: