伯克利 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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值