当前位置: 首页 > news >正文

伯克利 CS61A 课堂笔记 08 —— Strings and Dictionaries

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

目录

01 Strings 字符串

Ⅰ Strings are An Abstraction.

Ⅱ Strings Literals have Three Forms

Ⅲ String are Sequences

02 Dictionaries 字典

03 Dictionary Comprehensions 字典理解

附:词汇解释


01 Strings 字符串

Ⅰ Strings are An Abstraction.

>>> 'curry = lambda f: lambda x: lambda y: f(x, y)'
'curry = lambda f: lambda x: lambda y: f(x, y)'
>>> exec('curry = lambda f: lambda x: lambda y: f(x, y)')
>>> curry
<function <lambda> at 0x1003c1bf8>
>>> from operator import add
>>> curry(add)(3)(4)
7
Ⅱ Strings Literals have Three Forms
>>> 'I am string'
'I am string'
>>> '您好'
'您好'>>> "I've learned a lot from CS61A"
"I've learned a lot from CS61A">>> """The Zen of Python 
claims, Readability counts. 
Read more: import this."""
'The Zen of Python\nclaims, Readability counts.\nRead more: import this.'

① Single-quoted and double-quoted strings are equivalent.

② A backslash "escapes" the following character.

③ "Line feed" character represents a new line.

Ⅲ String are Sequences

Length and element selection are similar to all sequences.

However, the "in" and "not in" operators match substrings.

When working with strings, we usually care about whole words more than letters.

02 Dictionaries 字典

Dictionaries are collections of key-value pairs.

>>> numerals = {'I': 1, 'V': 5, 'X': 10}
>>> numerals
{'I': 1, 'V': 5, 'X': 10}>>> numerals['I']
1
>>> numerals[0]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: 0
>>> numerals['V']
5
>>> numerals['X']
10>>> list(numerals)
['I', 'V', 'X']
>>> numerals.values()
dict_values([1, 5, 10])
>>> list(numerals.values())
[1, 5, 10]
>>> sum(numerals.values())
16>>> {}
{}
>>> {1: {}}
{1: {}}
>>> {1: 'item'}
{1: 'item'}
>>> {1: ['first', 'second'], 3: 'third'}
{1: ['first', 'second'], 3: 'third'}
>>> d = {1: ['first', 'second'], 3: 'third'}
>>> d[1]
['first', 'second']
>>> d[3]
'third'>>> len(d)
2
>>> len(d[1])
2
>>> len(d[3])
5

Dictionary key do have two restrictions.

#Two keys cannot be equal
#There can be at most one value for a given key
>>> {1: 'first', 1: 'second'}
{1: 'second'}#A key of a dictionary cannot be a list or a dictionary(or any mutable type)
#[] or {}
>>> {[1]: 'first'}
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: unhashable type: 'list'>>> {{}: 'first'}
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: unhashable type: 'dict'

The first restriction is part of the dictionary abstraction.

The second restriction is tied to Python's underlying implementation of dictionaries.

If you want to associate multiple values with a key, store them all in a sequence value.

03 Dictionary Comprehensions 字典理解

An expression that evaluates to a dictionary using this evaluation procedure:

① Add a new frame with the current frame as its parent.

② Create an empty result dictionary that is the value of the expression.

③ For each element in the iterable value of <iter exp>:

A. Bind <name> to that element in the new frame from step 1.

B. If <filter exp> evaluates to a true value, then add to the result dictionary an entry that

pairs the value of <key exp> to the value of <value exp>.

Example 1: Indexing

def index(keys, values, match):"""Return a dictionary from keys to a list of values for which match(k, v) is a true value.>>> index([7, 9, 11], range(30, 50), lambda k, v: v % k == 0){7: [35, 42, 49], 9: [36, 45], 11: [33, 44]}"""return {k: [v for v in values if match(k, v) for k in keys]}

附:词汇解释

quote / kwoʊt / 引号

single-quote 单引号

double-quote 双引号

equivalent / ɪˈkwɪvələnt / 等同的

habitation 住所

backslash / ˈbækslæʃ / 反斜杠符号

escape / ɪˈskeɪp / 逃跑

mutable / ˈmjuːtəb(ə)l / 可变的

unhashable 不可哈希的

traceback 回溯

underlying 下层的,底层的

pair 配对

http://www.lryc.cn/news/536338.html

相关文章:

  • 机器学习 - 理解偏差-方差分解
  • Springboot引入(集成)Mybatis-plus
  • stm32 lwip tcp服务端频繁接收连接失效问题解决(tcp_recved)
  • java项目之基于SSM会议管理系统的设计与实现源码(ssm+mysql)
  • 腿足机器人之二- 运动控制概览
  • 【MySQL】基础篇
  • vscode环境搭建
  • tp whereOr用法2
  • 前端面试题目---页面抖动的原因、如何避免、如何解决
  • Spring Boot整合DeepSeek实现AI对话(API调用和本地部署)
  • DeepSeek 的 API 服务引入 WPS Office
  • 在Vue中,JavaScript数组常用方法,添加,插入,查找,删除等整理
  • 树莓派上 基于Opencv 实现人脸检测与人脸识别
  • Unity 接入Tripo 文生模型,图生模型
  • Redis常见数据结构
  • fps动作系统9:动画音频
  • 十四、GitLab 流水线自动化部署之 Windows Server
  • 数据库数据恢复—MongoDB丢失_mdb_catalog.wt文件导致报错的数据恢复案例
  • mysql8.0使用MGR实现高可用与利用MySQL Router构建读写分离MGR集群
  • 基于Ubuntu2404搭建k8s-1.31集群
  • Golang的图形编程应用案例
  • PostgreSQL 错误代码 23505 : ERROR: duplicate key value violates unique constraint
  • 基于SpringBoot和PostGIS的省域“地理难抵点(最纵深处)”检索及可视化实践
  • MySQL InnoDB引擎 MVCC
  • 服务器使用centos7.9操作系统前需要做的准备工作
  • 【Prometheus】prometheus结合cAdvisor监控docker容器运行状态,并且实现实时告警通知
  • 【Stable Diffusion模型测试】测试ControlNet,没有线稿图?
  • 算法刷题-数组系列-卡码网.区间和
  • Druid GetConnectionTimeoutException解决方案之一
  • 【JavaScript爬虫记录】记录一下使用JavaScript爬取m4s流视频过程(内含ffmpeg合并)