伯克利 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.mzph.cn/news/895502.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于 GEE 计算研究区年均地表温度数据

目录 1 代码解析 2 完整代码 3 运行结果 1 代码解析 &#xff08;1&#xff09;定义研究区&#xff1a; // 研究区的范围需要自己提前上传 var dataset table;// 将研究区显示在中心&#xff0c;后面的数字为缩放等级&#xff0c;范围从1 - 24 Map.centerObject(dataset,…

docker compose快速部署kafka-connect集群

先部署kafka集群&#xff0c;启动 参考&#xff1a;docker compose部署kafka集群-CSDN博客 创建timezone文件&#xff0c;内容填写Asia/Shanghai 再部署kafka-connect集群 networks: net: external: true services: kafka-connect1: restart: always image:…

Hutool - BloomFilter:便捷的布隆过滤器实现

1. 布隆过滤器简介 布隆过滤器&#xff08;Bloom Filter&#xff09;是一种空间效率极高的概率型数据结构&#xff0c;用于判断一个元素是否存在于一个集合中。它的优点是空间效率和查询时间都远远超过一般的算法&#xff0c;但缺点是有一定的误判率&#xff0c;即判断元素存在…

日常知识点之遗留问题梳理(定时器/时间轮定时器)

1&#xff1a;简单基础 定时器的核心知识点&#xff0c;对我来说就是获取当前时间和设置回调函数。 简单练习&#xff1a; ​ c语言通过gettimeofday 获取当前时间并进行处理 ​ 回调函数的定义&#xff08;函数参数有必要适当存储&#xff09; typedef void(Timerfunc)(vo…

Python + WhisperX:解锁语音识别的高效新姿势

大家好&#xff0c;我是烤鸭&#xff1a; 最近在尝试做视频的质量分析&#xff0c;打算利用asr针对声音判断是否有人声&#xff0c;以及识别出来的文本进行进一步操作。asr看了几个开源的&#xff0c;最终选择了openai的whisper&#xff0c;后来发现性能不行&#xff0c;又换了…

$ npx electron-forge import 一直报权限问题 resource busy or locked,

jackLAPTOP-7DHDAAL0 MINGW64 /e/project/celetron-project/my-electron-app (master) $ npx electron-forge import > Checking your system > Checking git exists > Checking node version > Checking packageManager version √ Found node22.14.0 √ Found gi…

mapbox 从入门到精通 - 目录

&#x1f468;‍⚕️ 主页&#xff1a; gis分享者 &#x1f468;‍⚕️ 感谢各位大佬 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍⚕️ 收录于专栏&#xff1a;mapbox 从入门到精通 文章目录 一、&#x1f340;总目录1.1 ☘️ mapbox基础1.2 ☘️…

Kotlin 2.1.0 入门教程(十五)继承、重写、派生类初始化顺序

继承 所有类都有一个共同的超类 Any&#xff0c;对于没有声明超类型的类来说&#xff0c;Any 是其默认的超类&#xff1a; // 隐式继承自 Any。 class ExampleAny 有三个方法&#xff1a;equals()、hashCode() 和 toString()。因此&#xff0c;所有类都定义了这些方法。 默认…

sqlilabs--小实验

一、先盲注判断 ?id1 and sleep(2)-- 如果发现页面存在注点&#xff0c;使用时间盲注脚本进行注入 import requestsdef inject_database(url):name for i in range(1, 20): # 假设数据库名称长度不超过20low 48 # 0high 122 # zmiddle (low high) // 2while low &l…

【数字】异步FIFO面试的几个小问题与跨时钟域时序约束

入门数字设计的时候&#xff0c;跨时钟域的数据处理是绕不开的课题&#xff0c;特别是多比特数据跨时钟域时&#xff0c;都会采用异步FIFO的方法。 异步FIFO中涉及较多的考点这里记录几个以供大家参考。 1. 异步FIFO的空满判断分别在哪个域&#xff1f; 根据异步FIFO的结构&…

浅谈Java Spring Boot 框架分析和理解

Spring Boot是一个简化Spring开发的框架&#xff0c;它遵循“约定优于配置”的原则&#xff0c;通过内嵌的Tomcat、Jetty或Undertow等容器&#xff0c;使得开发者能够快速构建独立运行的、生产级别的基于Spring框架的应用程序。Spring Boot包含了大量的自动配置功能&#xff0c…

算法06-回溯算法

一、回溯算法详解 回溯算法是一种通过逐步构建解决方案来解决问题的算法。它通常用于解决组合问题、排列问题、子集问题等。回溯算法的核心思想是“试错”&#xff0c;即在每一步尝试所有可能的选项&#xff0c;如果发现当前选择无法达到目标&#xff0c;就回退到上一步&#…

RabbitMQ学习—day2—安装

目录 普通Linux安装 安装RabbitMQ 1、下载 2、安装 3. Web管理界面及授权操作 Docker 安装 强力推荐学docker&#xff0c;使用docker安装 普通Linux安装 安装RabbitMQ 1、下载 官网下载地址&#xff1a;https://www.rabbitmq.com/download.html(opens new window) 这…

降本增效 - VGF 构建轻量高性能日志管理平台

VFG 技术架构 Filebeat 接收Syslog &#xff0c;并进行日志分段&#xff0c;VictoriaLogs 持久化存储日志 &#xff0c;Grafana 可视化、数据查询、告警、数据导出。 为什么要用VictoriaLogs &#xff1f; 与Elasticsearch /Grafana Loki相比几十倍的CPU/内存/存储资源占用的…

初识camel智能体(一)

同目录下配置环境变量.env&#xff0c;内容如下&#xff0c; apikey从魔搭社区获取 QWEN_API_KEY4ff3ac8f-aebc******** 先上干货代码&#xff0c;主代码如下&#xff1a; from colorama import Forefrom camel.societies import RolePlaying from camel.utils import prin…

介绍 Liquibase、Flyway、Talend 和 Apache NiFi:选择适合的工具

在现代软件开发中&#xff0c;尤其是在数据库管理和数据集成方面&#xff0c;选择合适的工具至关重要。本文将介绍四个流行的工具&#xff1a;Liquibase、Flyway、Talend 和 Apache NiFi&#xff0c;分析它们的应用、依赖以及如何选择适合的工具。 1. Liquibase 简介&#xff…

Docker使用指南与Dockerfile文件详解:从入门到实战

Docker使用指南与Dockerfile文件详解:从入门到实战 文章目录 **Docker使用指南与Dockerfile文件详解:从入门到实战****引言****第一部分:Docker 核心概念速览****1. Docker 基础架构****2. Docker 核心命令****第二部分:Dockerfile 文件深度解析****1. Dockerfile 是什么?…

Qt工作总结03 <qSort按某一属性进行排序>

1. 代码样例 QList<QGraphicsTextItem *> Lst;qSort(Lst.begin(),Lst.end(),[](const QGraphicsTextItem *itemA,const QGraphicsTextItem *itemB) {return itemA->toPlainText().toDouble() < itemB->toPlainText().toDouble(); }); 2. 参考 QList 按结构体…

深度学习|表示学习|Instance Normalization 全面总结|26

如是我闻&#xff1a; 1. Instance Normalization&#xff08;IN&#xff09; Instance Normalization&#xff08;IN&#xff09;最早由 Ulyanov et al.&#xff08;2017&#xff09; 提出&#xff0c;主要用于 风格迁移&#xff08;Style Transfer&#xff09; 任务。它的核…

如何保持 mysql 和 redis 中数据的一致性?PegaDB 给出答案

MySQL 与 Redis 数据保持一致性是一个常见且复杂的问题&#xff0c;一般来说需要结合多种策略来平衡性能与一致性。 传统的解决策略是先读缓存&#xff0c;未命中则读数据库并回填缓存&#xff0c;但方式这种维护成本较高。 随着云数据库技术的发展&#xff0c;目前国内云厂商…