伯克利 CS61A 课堂笔记 07 —— Lists

本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。

目录

01 Lists 列表

02 Containers 容器

03 For Statements For 语句

04 Ranges 范围

05 List Comprehensions 列表理解

06 Box-and-Pointer Notation 箱点标记

Ⅰ The Closure Property of Data Types

Ⅱ Box-and-Pointer Notation in Environment Diagrams

07 Slicing 切片

08 Processing Container Values 处理容器值

Ⅰ sum(iterable[ , start]) -> value

Ⅱ max(iterable[ , key = func]) -> value and max(a, b, c, ... [ , key = func]) -> value

Ⅲ all(iterable) -> bool

附:词汇解释


01 Lists 列表

>>> digits = [0, 5, 2, 6]
>>> digits = [2-2, 1+1+3, 2, 2*3]

#The number of elements
>>> len(digits)

#An element selected by its index
>>> digits[3]
>>> getitem(digits, 3)

#Concarenation and repetition
>>> [2, 7] + digits * 2
>>> add([2, 7], mul(digits, 2))

#Nested lists
>>> pairs = [[10, 20], [30, 40]]
>>> pairs[1] #[30, 40]
>>> pairs[1][0] #30

02 Containers 容器

Built-in operators for testing whether an element appears in a compound value.

>>> digits = [0, 5, 2, 6]

>>> 0 in digits
True
>>> 1 not in digits
True
>>> not(1 in digits)
True

>>> '5' == 5
False
>>> '5' in digits
False
>>> [0, 5] in digits
False
>>> [0, 5] in [[0, 5], 2, 6]

03 For Statements For 语句

for <name> in <expression>:
    <suite>

① Evaluate the header <expression>, while must yield an iterable value (a sequence).

② For each element in that sequence, in order:

​        A Bind <name> to that element in the current frame.

​        B Execute the <suite>.

def count(s, value):
    '''Count the number of times that value occurs in sequence s.
    
    >>> count([1, 2, 1, 3, 1], 1)
    3
    '''
    
    total = 0
    #Name bound in the first frame of the current environment.
    for element in s: 
        if element == value:
            total += 1
     return total   

Sequence unpacking in for statements.

pairs = [[1, 2], [2, 3], [2, 2], [1, 1]]

count = 0
for x,y in pairs:
    if x == y:
        count += 1

04 Ranges 范围

A range is a sequence of consecutive integers.

Length: ending value - starting value

Element selection: starting value + index

>>> list(range(-2, 2))
[-2, -1, 0, 1]

#Range with a 0 starting value
>>> list(range(4))
[0, 1, 2, 3]
def sumBelow(n):
    total = 0
    for i in range(n):
        total += i
    return total    

def cheer():
    for _ in range(3):
        print('Go Bears!')

05 List Comprehensions 列表理解

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> [letters[i] for i in [3, 4, 6, 8]]
['d', 'e', 'g', 'i']

>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]
>>> [x for x in odds if 25 % x == 0]
[1, 5]
def divisors(n):
    return [1] + [x for x in range(2, n) if n % x == 0]

>>>divisors(1)
[1]
>>>divisors(4)
[1, 2]
>>>divisors(9)
[1, 3]
>>>divisors(12)
[1, 2, 3, 4, 6]

06 Box-and-Pointer Notation 箱点标记

Ⅰ The Closure Property of Data Types

A method for combing data values satisfies the closure property if the result of combination can itself be combined using the same method.

Closure is powerful because it permits us to create hierarchical structures.

Hierarchical structures are made up of parts, while themselves are made up of parts, and so on.

Attention: Lists can contain lists as elements (in addition to anything else).

Ⅱ Box-and-Pointer Notation in Environment Diagrams

Lists are represented as a row of index-labeled adjacent boxes, one per element.

Each box either contains a primitive value or points to a compound value.

07 Slicing 切片

>>> odds = [3, 5, 7, 9, 11]
>>> odds[1:3]
[5, 7]
>>> odds[:3]
[3, 5, 7]
>>> odds[1:]
[5, 7, 9, 11]
>>> odds[:]
[3, 5, 7, 9, 11]

Slicing creates new values.

08 Processing Container Values 处理容器值

Several built-in functions take iterable arguments and aggregate them into a value.

Ⅰ sum(iterable[ , start]) -> value

Return the sum of an iterable of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the iterable is empty, return start.

>>> sum([2, 3, 4])
9
>>> sum([2, 3, 4], 5)
14

>>> [2, 3] + [4]
[2, 3, 4]
>>> sum([[2, 3], [4]], [])
[2, 3, 4]
Ⅱ max(iterable[ , key = func]) -> value and max(a, b, c, ... [ , key = func]) -> value

With a single iterable argument, return its largest item.

With two or more arguments, return the largest argument.

>>> max(range(5))
4
>>> max(0, 1, 2, 3, 4)
4
>>> max(range(10), key=lambda x: 7-(x-4)*(x-2))
3
>>> (lambda x: 7-(x-4)*(x-2))(3)
8
>>> (lambda x: 7-(x-4)*(x-2))(2)
7
>>> (lambda x: 7-(x-4)*(x-2))(4)
7
>>> (lambda x: 7-(x-4)*(x-2))(5)
4
Ⅲ all(iterable) -> bool

Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.

>>> bool(5)
True
>>> bool(True)
True
>>> bool(-1)
True
>>> bool(0)
False
>>> bool('hello')
True
>>> bool('')
False
>>> range(5)
range(0, 5)
>>> [x<5 for x in range(5)]
[True, True, True, True, True]
>>> all([x<5 for x in range(5)])
True
>>> all(range(5))
False

附:词汇解释

yield / jiːld / 产生、iterable 可迭代的、consecutive / kənˈsekjətɪv / 连续的,不间断的、comprehension 理解,领悟、odd 奇数的、divisor/ dɪˈvaɪzər / 除数,因子、index-labeled 标记指数、adjacent / əˈdʒeɪs(ə)nt / 相邻的、primitive value 原始值、compound value 复合值、notation 标记

closure property 闭包性质:在数学中,指一个集合在某种运算下的封闭性,即该运算的结果仍属于该集合

hierarchical / ˌhaɪəˈrɑːrkɪkl / structure 层次结构:是按层次划分的数据元素的集合,指定层次上元素可 以有零个或多个处于下一个层次上的直接所属下层元素

CS61A 是加州大学伯克利分校的一门计算机科学入门课程,重点在于教授学生如何像程序员一样思考。它覆盖了函数式编程、面向对象编程以及一些基础的数据结构等内容。通常这门课使用 Python 编程语言作为教学工具。 下面是一个基于 CS61A 内容的学习路线图,帮助你系统化地掌握其核心知识点: --- ### 学习阶段及内容安排 #### 第一部分:计算思维与Python基础知识 - **第一章** - 计算机程序的本质理解;简单表达式的求值过程。 - 掌握变量赋值、基本数据类型(string, number)及其运算规则。 #### 第二部分:高阶函数和递归 - 函数定义(def关键字),局部变量作用域链。 - 迭代 vs 递归 —— 解决问题的不同思维方式对比分析。 - Lambda匿名函数的应用场合探讨。 - 高阶函数(map/filter/reduce etc.)的概念引入及相关案例练习。 #### 第三部分:抽象能力培养 - 数据抽象(Data Abstraction): 将复杂信息简化成易于管理的形式表示出来。 - ADT(Abstract Data Types)- 用户视角下的封装原则体现。 - 树(Tree)/列表(Lists)等复合型数据类型的构建技巧讲解。 #### 第四部分:面向对象设计思想(OOD) - 类(Class)与实例(Instance)之间的关系建立。 - 继承(Inheritance)特性说明及其优缺点权衡考量。 - 构造器(Constructor)__init__() 的工作原理剖析。 #### 第五部分:序列(Seqences) 和树(Trees) 深入探究 - 列表推导式(List Comprehensions)高效编写简洁优雅代码的艺术展现。 - 字符串(String Methods)常用操作汇总分享。 - 广度优先搜索(BFS)、深度优先搜索(DFS)算法逻辑阐述并通过实际例子加以巩固强化记忆效果。 #### 最终项目实践环节(Project Section): 选择合适的小型工程项目主题进行完整生命周期开发体验全流程模拟训练。(比如文字冒险游戏Text Adventure Game) --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值