伯克利 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.pswp.cn/news/895502.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/895502.shtml
英文地址,請注明出處:http://en.pswp.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;目前國內云廠商…