diff --git a/.gitignore b/.gitignore index 9a697e0..71c3ca5 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,6 @@ __pycache__/* *~ .DS_Store .idea/* -*_build* \ No newline at end of file +*_build* +.vscode/ +**/__pycache__/* \ No newline at end of file diff --git a/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md b/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md index 001a98c..58452c5 100644 --- a/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md +++ b/Python/Module1_GettingStartedWithPython/GettingStartedWithPython.md @@ -4,131 +4,131 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Basic description of the Python programming language, Difficulty: Easy, Category: Background :keywords: python, install, basics, scripts, interpreter, foundations -``` + -# Introducing the Python Programming Language +# 介绍Python编程语言 -In this section we will learn +在本节中我们将学习 - - What Python is. - - What it means to "install Python" on your computer. - - How one writes and executes Python code. + - Python是什么。 + - “安装Python”具体意味着什么。 + - 如何写和执行Python代码。 -## What is Python? -**Python is a programming language**. That is, it provides us with a strict set of grammatical rules that correspond to well-defined instructions that a computer will obey. The tremendous value of this is that we can write text documents that are relatively simple and intuitive for humans to read, and yet can inform the computer to perform precise operations. Python **code** is simply text that conforms to the Python language. +## Python是什么? +**Python是一门编程语言**。具体来讲,Python为我们提供一组严谨的语法规则;每条规则都对应一组计算机会执行的明确命令。这将允许我们编写一些即易读,又能提供具体命令给计算机的文本。所谓的Python**代码**其实就是符合Python语法的文本。 -For example, the following text obeys the rules of the Python language: +比如说,以下的文本就符合Python的语法规则: ```python x = 2 + 3 print('2 + 3 = {}'.format(x)) ``` -According to the Python language, it will instruct the computer to: +根据Python的定义,它将指令计算机去: - - compute 2 + 3 - - assign the resulting value (5) to a variable `x`, in memory - - access the value of `x`, and print to the computer's screen: '2 + 3 = 5' + - 计算 2 + 3 + - 在内存中设定一个函数 `x` 为计算的结果(5) + - 访问 `x` 的值,并在计算机屏幕上显示:“2 + 3 = 5” -An example of code that **does not** obey Python's rules is: +一个**不符合**Python规则的例子: ```python x = 2 ~ 3 ``` -because character `~` has no meaning in the Python language when it is placed between two integers. +原因是,根据Python定义,夹在两个整数中间的符号 `~` 没有任何意义。 -To "learn Python" thus entails learning the grammatical rules specified by the Python language, and the computer instuctions that they map to. Additionally, you will want to familiarize yourself with many of the convenient tools that are "pre-written" and come with the Python language; they are part of the so-called standard library. +因此,“学习Python”意味着学习Python语言的语法规则以及这些规则对应的计算机指令。同时,你也需要了解已经“提前写好”的,极其方便的Python自带的工具;这些工具是所谓Python标准库的一部分。 -Given this basic understanding of what the Python programming language is, we now want to know how to use our Python code to send instructions to the computer. The most basic way of doing this is to: +有了对Python语言的基本理解后,我们现在要学习如何使用我们的Python代码去给计算机发送指令。最基本的方法是: - - Write a Python "script": a text file containing Python code. - - Pass this text file to a **Python interpreter**, which will instruct the computer to carry out the operations described by the code. + - 写Python“脚本”:一个包含Python代码的文本。 + - 将这个文本送到**Python直译器**(Python Interpreter)中。直译器将告诉计算机去执行代码描述的工作。 -## Python Scripts -You can save the the valid code from the preceding section in a text file using a simple text editor, and *voilà* you have written a **Python script**: a text file containing Python code. It is standard to save this text file using the suffix `.py` (e.g. `my_code.py`), rather than the familiar `.txt` (e.g. `my_text.txt`). There is nothing special about the `.py` suffix; it simply helps differentiate files that contain Python code from run-of-the-mill text files, which contain plain English. +## Python脚本 +你可以用任意一个文本编辑器将前文的能用的代码存到一个文本文件中。就像这样,你写好了一个**Python脚本**:一个包含Python代码的文本文件。标准情况下,Python代码的后缀都是 `.py`(比如说 `my_code.py`),而不是常见的 `.txt`(例如 `my_text.txt`)。这个 `.py` 后缀没有任何特殊的;这仅仅是为了帮助用户区分包含Python代码的文本文件和其他正常的包含普通文章的文本文件。 -Although you can use simple text editors to write Python scripts (e.g. notepad (Win), TextEdit (Mac), nano (Linux)), there are much more sophisticated editors that provide an "integrated development environment" (IDE) for writing code. An IDE, configured to support Python, will warn you if you have written code that violates Python's grammar rules, similar to the way word processing software warns you if you have made a spelling mistake. More on IDEs in a later section. +虽然你可以使用基本的文本编辑器去写Python脚本(如notepad(Windows),TextEdit(Mac),nano(Linux)),但是你也可以使用更加复杂的提供“集成开发环境”(Integrated Development Environment,也就是IDE)的编辑器来写代码。一个为Python配置的IDE会警告不符合Python语法的代码,就像Word这类文字处理软件会提醒你的错误拼写一样。我们会在之后的一节里详细讨论IDE。
-**WARNING**: +**警告**: + +不要使用像Microsfot Word这样的传统文字处理程序来编写代码。这些程序会“静默”地对你打出的字符进行修改,如双引号的种类。这会导致你的代码出现错误。 -Do not use word processing programs, like Microsoft Word, to write code. They will "silently" change the characters written in your file, such as the type of quotation marks being used. This will cause errors in your code. +译者注:在写Python代码时一定要记得使用英文输入法。Python直译器并不会理解中文的双引号 “” 或单引号 ‘’
-Now that you have a Python script, how do you get the computer to read it and follow its instructions? You will need to install a **Python interpreter** on your computer to accomplish this. This is what people mean, whether they know it or not, when they tell you to "install Python" on your computer. +在有一个Python脚本后,该如何让电脑读取并执行脚本的指示呢?你需要在你的计算机上安装一个**Python直译器**。当人们说你需要“安装Python”的时候,这就是他们具体的意思。 - -## What is a Python Interpreter and What Does it Mean to "Install Python"? -A Python interpreter is any computer program that is capable of doing the following: +## Python直译器是什么?“安装Python”意味着什么? - - Read in a text file (e.g. `my_code.py`). - - Parse the text and determine if it obeys the rules of the Python language (the interpreter will raise an error if the rules are not obeyed). - - Translate the parsed text into instructions, according to the Python language's specifications. - - Instruct the computer to carry out the tasks. - - As a whole, a Python script is executed from top-to-bottom by the interpreter. +Python直译器泛指任何可以执行以下的电脑程序: -The first Python interpeter was written in the programming language C, and is known as CPython. Accordingly, **the CPython interpreter is the official interpreter of the Python language**. Any new rules/features that are introduced to the Python language are guaranteed be implemented in the [CPython code base](https://github.com/python/cpython). + - 读取文本文件(如 `my_code.py`)。 + - 解析其文本并反馈文本是否符合Python语言的语法规则(如果不符合,直译器会报错)。 + - 指示计算机去执行文本描述的任务。 + - 总体而言,Python直译器将从上到下执行脚本。 + +世界上第一个Python直译器是用C编程语言写的,因此其被命名为CPython。所以**CPython直译器是最官方的Python语言直译器**。任何新的Python特征或规则一定会在[CPython代码库](https://github.com/python/cpython)中实现。
-**Note**: +**注**: -Python interpreters have been in written programming languages other than C, like in Java (Jython) and Go (Grumpy). These are not guaranteed to be up-to-date with the latest specifications of the Python language, and are rarely used in comparison to the CPython interpreter. +当然,Python直译器也存在于其他不是C的编程语言中,如Java(Jython)和Go(Grumpy)。这些直译器并不能保证实现最新的Python规范,因此很少有人会将它们和CPython直译器对比。
-**About Installing Python**: +**关于安装Python**: -Do not download and install Python from python.org. There isn't anything wrong with this, but a later section will provide you with explicit instructions for installing Python on your machine. +不要从python.org下载和安装Python。这样做没有任何错,但是本文后面的一节将提供详细的Python安装指示。
-If you "install Python on your computer" from [python.org](https://www.python.org/downloads/release/python-363/), you are essentially downloading an executable program onto your machine that operates as a Python interpreter. On Windows, for instance, this program is called `python.exe`. This program is the result of the aforementioned CPython code, and it is capable of performing the all of the tasks of a Python interpreter. Additionally, you are downloading a large suite of useful tools and functions that you can utilize in your code. This is known as the Python standard library; take a moment to look over its contents [here](https://docs.python.org/3/library/index.html#the-python-standard-library). +如果你从[python.org](https://www.python.org/downloads/release/python-363/)“在你的计算机上安装了Python”,你在做的基本就是下载一个满足Python直译器规范的可执行文件。比如在Windows上,这个程序叫做 `python.exe`。这个程序就是之前提到的CPython代码的产物,其可以执行任何Python直译器的工作。同时,你也在下载一大组可以用于你自己代码里的工具和函数。这些工具和函数叫做Python标准库;花一些时间去了解[标准库](https://docs.python.org/3/library/index.html#the-python-standard-library)的内容。 -Once you have a Python interpreter installed on your machine, using it to execute a Python script is quite simple. Assume for the sake of simplicity that the `python` interpreter program and `my_script.py` are in the same directory (a.k.a 'folder') in your computer. Then, in a terminal (`cmd.exe` for Windows) you can execute the following command: +当你在计算机上安装了一个Python直译器后,使用它去执行Python脚本并不困难。为简化我们的讨论,假设叫做 `python` 的直译器程序和 `my_script.py` 都在你的计算机中同一个文件夹内(叫做 `folder`)。那么,在命令行(对Windows而言就是 `cmd.exe`)中,你可以执行以下指令: ```shell python my_script.py ``` -this will instruct the Python interpreter program `python` to read your text file `my_script.py`, ensure that your code obeys all of the grammatical rules specified by the Python language, and then send instructions to your computer in accordance with the code that it reads. If your script simply contains the code `print("hello world")`, then the text `hello world` will appear in your terminal window, as expected. +这将指示Python直译器程序 `python` 去读取你的文本文件 `my_script.py`,确保里面的代码符合所有Python语言的语法规则,并指示你的计算机去执行和文本相应的指令。如果你的脚本仅仅包含代码 `print("hello world")`,那么你的命令行自然会显示字符串 `hello world`。 -In practice, you will be able to simply execute `python my_script.py` in any directory, and your computer will know where to look to find the `python` program. This will be set up during the installation process. +在实际使用中,不管你从任何文件夹中执行 `python my_script.py`,你的计算机也应该会知道如何去找到名为 `python` 程序。相应的设置会在安装过程中完成。 -It may be confusing to think that the Python language is interpreted by using a program written in another language. How, then, is that language interpreted? The answer, in the case of CPython, is that C code need not be interpreted; programs exist for Windows, Mac, and Linux that can translate C code directly into machine instructions. - +理解Python语言是被一个用另外语言编写的程序来直译的事实可能比较绕脑。如果是这样,那另外那个语言是怎么被直译的呢?在CPython的情况下,答案就是C代码并不会被直译;有程序存在于Windows,Mac,和Linux上可以直接将C代码翻译成电脑直接执行的机器指令。 -## Why Python? +## 为什么选择Python? -Python has become a hugely popular programming language. In fact, it is likely the [most popular introductory language at universities](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext). First and foremost, its syntax is designed to be intuitive and readable. For example, the following Python code sums the numbers 0-9, and prints the result: +Python已经成为了一个极其流行的编程语言。事实上,它可能是[最流行的大学编程入门语言](https://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext)。首先,Python的句法非常易懂易读。比如说,接下来的代码会求数字 0-9 的和,并打印结果: ```python a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(sum(a)) ``` -This can be reproduced by the following C++ code, which is arguably less-intuitive: +同样的工作可以用以下的C++代码达成,但是这难懂很多: ```cpp #include #include @@ -136,21 +136,21 @@ This can be reproduced by the following C++ code, which is arguably less-intuiti int main() { std::vector a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - std::cout << std::accumulate(a.begin(), e.end(), 0) << std::endl; + std::cout << std::accumulate(a.begin(), a.end(), 0) << std::endl; } ``` -As such, Python is a language that is conducive to rapidly prototyping and testing code. Additionally, it is open-sourced: it is free to use, anyone can participate in improving/maintaining the language, and many people create new libraries that add tremendous functionality to the language. Thus, Python has become exceptionally popular especially among scientists, engineers, and other researchers. +因此,Python作为一门语言很方便快速编写和测试新代码。同时,Python是开源的;你可以免费使用它,任何人都可以参与到维持或改善这门语言中,且大家创造了很多给Python提供了大量功能的第三方模组。因此,Python在科学家,工程师,和其他研究者中极其流行。 -We will be relying heavily on Python and a library for doing optimized numerical computations, called NumPy, throughout this course. +在本资源中我们会使用Python和高度优化的数字工作模组NumPy。 -## Summary +## 总结 -- Python is a programming language - it provides us with a simple set of grammatical rules that allow us to write human-readable text, which can be translated unambiguously to instruct a computer to perform tasks. -- Python code is text that conforms to the Python language. -- A Python script is a text file containing Python code. Traditionally such a file will be saved using the suffix `.py`. -- A Python interpreter is a program that is capable of reading and parsing a text file, and translating the code into machine instructions, as specified by the Python language. -- To "install Python" onto you machine boils down to saving a functioning Python interpreter onto your machine. -- The official Python interpreter is a program written in the language C, and is known as the CPython interpreter. -- The "standard library" is a large collection of tools and functions that comes packaged with the CPython interpreter. +- Python是一门编程语言——它为我们提供一组简单的语法规则来编写既可以让人看懂也可以准确翻译到计算机指令的文本。 +- Python代码是任何符合Python语言标准的文本。 +- Python脚本是一个包含Python代码的文本文件。这种文件根据命名标准都使用后缀 `.py`。 +- Python直译器是一个能够读取和分析文本文件并根据Python语言的规则将其中的代码翻译成计算机指示的程序。 +- "安装Python”归根结底就是将Python直译器下载到你的计算机上。 +- 官方的Python直译器是一个用C语言编写的程序,叫做CPython直译器。 +- Python"标准库“是和CPython直译器一起包装的一组庞大的工具和函数。 diff --git a/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md b/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md index c1ada19..3fd82ae 100644 --- a/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md +++ b/Python/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.md @@ -4,84 +4,79 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Integrated Development Environments, Difficulty: Easy, Category: Tools :keywords: python, introduction, IDE, PyCharm, VSCode, Jupyter, recommendation, tools -``` + -# Setting Up a Development Environment -## What You Will Learn +# 设置开发环境 +## 你将学到什么 -- An IDE is a sophisticated text editor that allows you edit, run, and debug code. -- The Python shell is an interface for typing Python code and executing it directly in your computer's terminal. -- The IPython shell is a much nicer version of the Python shell - it provides syntax highlighting, autocompletion, and other features. -- The Jupyter Notebook is a powerful tool for prototyping and experimenting with code, as well as visualizing data and writing nicely-formatted text. We will be using this throughout the course. +- 集成开发环境(IDE)是一套用来编辑,运行,和调试代码的复杂的文本编辑器。 +- Python壳(shell)是一个用以输入和直接在计算机命令行中运行Python代码的接口。 +- IPython壳是一个更加完善的Python壳——它提供语法高亮,自动完成,以及其它有用的功能。 +- Jupyter记事本是用来编写,测试新代码的强大工具。它同时也可以用来可视化数据和编写格式化的文本。我们将会在本资源中经常使用它。 -## Integrated Development Environments -In Section 1 of this module, we learned that a Python script is simply a text file that contains Python code. Aside from using a `.py` suffix for the filename, there is nothing that differentiates this sort of file from any other text file. That being said, it is not a good idea to use a simple text editor to write Python code (and it is a big mistake use word-processing software, like Microsoft Word, to do so). Instead we want an "integrated development environment" (IDE) that will facilitate our code-writing. +## 集成开发环境(IDE) +在本模组的第一节中,我们了解了Python脚本仅仅是包含Python代码的文本文件这一事实。除了使用 `.py` 为文件后缀名之外,Python脚本对比其它文本文件没有什么特殊的特征。话说如此,使用文本编辑器来编写Python代码很不效率(而使用Microsoft Word这样的文字处理软件是万万不可取的)。我们需要一个“集成开发环境”(IDE)来帮助我们开发代码。 -First and foremost, a good IDE will provide a text editor that will: +首先,一个好的IDE会提供拥有如下功能的文本编辑器: -- check your code for syntax errors (a misspelled function name, a reference to an undefined variable, etc) -- colorize your code so that it is easy to distinguish, for instance, numbers from character strings. -- enable you to easily look up documentation and definitions for functions that you are using. -- autocomplete the names of variables and functions as you are typing them. +- 检查你的代码并标记语法错误(如拼错的函数名,不存在的变量,等等) +- 彩色化你的代码来使其更容易分辨。比如说,这可以帮助你区分数字和字符串。 +- 允许你轻松地查阅函数的定义和说明文件。 +- 在你输入变量和函数时自动完成它们的名字。 -An IDE also often provides debugging tools so that you can test your code; it will also typically interface with version-control software, like Git, so that you can keep track of versions of your code as you modify it. We will not discuss these useful, but more advanced features here. +很多IDE也会提供帮助你测试你的代码的调试工具以及帮助你在修改代码的同时记录代码版本的版本控制软件(version-control software)(如Git)。虽然它们很有用,我们在此并不讨论这些高级功能。 -### Recommended IDEs -There are many excellent IDEs that can be configured to work well with Python. Two IDEs that we endorse are: +### 推荐的IDE +市面上有很多IDE支持Python代码。我们在这里推荐两个: -[PyCharm](https://www.jetbrains.com/pycharm/download): A powerful IDE dedicated to Python. +[PyCharm](https://www.jetbrains.com/pycharm/download): 一个专门针对Python开发的强大IDE。 -**Pros** +**好处** -- works well out-of-the-box -- long-supported by professionals and thus is very reliable -- highly configurable -- fully-featured +- 下载即用,无需太多设置就很好用 +- 有职业人员的长期支持,因此很可靠 +- 可以进行深层次的设置 +- 全功能,包括极棒的调试器,适应语境的“Intellisense”,类型推论 +- 免费的“社区版本”(community version)已经非常强大和活跃 -**Cons** +**坏处** - - can be resource-heavy, especially for a laptop - - may be overwhelming to new users (but has good documentation and tutorials) - -[Visual Studio Code](https://code.visualstudio.com/) with the [Python extension](https://code.visualstudio.com/docs/languages/python): A lightweight, highly customizable IDE. - -**Pros** + - 很耗资源,特别对手提电脑而言 + - 功能多导致新用户难以上手(但它有很好的教程和说明文件) + - 需要付费版的PyCharm才可以支持Jupyter记事本,因此对新用户不友好 -- lightweight and elegant -- works with many different languages, so you only need to familiarize yourself with one IDE -- a huge number of extensions can be downloaded to add functionality to the editor; these are created by a large community of open-source developers. +[Visual Studio Code](https://code.visualstudio.com/) 以及它的 [Python拓展](https://code.visualstudio.com/docs/languages/python): 一个轻便,宜定制的IDE。 -**Cons** +**好处** -- currently less polished and less powerful than PyCharm, although Microsoft is now formally supporting the Python extension -- can require some tinkering to get features working +- 轻便优雅 +- 完全免费 +- 支持其它的编程语言,就算你经常使用多种编程语言你也只需要学习使用一个IDE +- 有极其多的拓展可供下载以提供编辑器新功能;这些拓展是由一个大社区的开源开发者编写的 +- [支持Jupyter记事本](https://code.visualstudio.com/docs/python/jupyter-support),意味着你可以在记事本中享受VSCode的intellisense,调试器,和查看变量的功能 +**坏处** -
- -**Takeaway**: +- 设置VSCode来进行Python开发对新手而言可能相对复杂 +- 很多功能,如intellisense和类型推论,在PyCharm中更加完善和强大 -Integrated Development Environments (IDEs) provide powerful tools for helping you write well-formatted and typo-free code. We recommend using PyCharm Community Edition or Visual Studio Code (with the Python extension installed) for your Python IDE. -
+
-
- -**Jupyter Lab**: - -[Jupyter Lab](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html) is a new IDE that is being developed by the same team that develops the Jupyter Notebook. It aims to mix the polish and power of a traditional IDE, along with the convenience and great utility of the notebook environment. As of writing this, Jupyter Lab is still in the beta release phase. Given the massive popularity of Jupyter Notebook, Jupyter Lab will likely become a widely used IDE, quickly. +**经验**: -
+集成开发环境(IDE)提供强大的工具来帮助你编写格式化和无拼写错误的代码。本资源建议你使用PyCharm Community Edition或Visual Studio Code(加上Python拓展)作为你的Python IDE。 +
\ No newline at end of file diff --git a/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md b/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md index aa53eea..a71eb5b 100644 --- a/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md +++ b/Python/Module1_GettingStartedWithPython/Informal_Intro_Python.md @@ -4,132 +4,134 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Informal Introduction to Python, Difficulty: Easy, Category: Tutorial :keywords: python, installation, script, introduction, ipython, console, quick introduction -``` + -# An Informal Introduction to Python -Now that you have the Anaconda distribution of Python installed on your machine, let's write some simple Python code! We are going to forego writing a full Python script for now, and instead make use of a convenient tool for doing quick code scratchwork. The IPython console was installed as a part of Anaconda; it will allow us to build incrementally off of snippets of code, instead of having to execute an entire script all at once. +# 非正式的Python介绍 +在你下载好了Anaconda版本的Python之后,让我们来写一些简单的Python代码吧!我们暂时先不编写完整的Python脚本,而只用一个方便的工具——IPython命令行——来快速地尝试一些简单的代码。Anaconda一并安装了IPython命令行;这将帮助你一步步增加代码片段,而不是要一次性执行整个脚本。 -Let's open an IPython console. Open your terminal if you are a Mac/Linux user, or start `cmd.exe` if you are a Windows user. Now type `ipython` into the console and hit ``. You should see the following display on your screen: +让我们打开IPython命令行。如果你是Mac或者Linux用户,打开你的命令行;如果你是Windows用户,打开 `cmd.exe`。输入 `ipython` 并敲击回车,你应该可以在屏幕上看到接下来的内容: ![IPython console example](attachments/ipython_0.PNG) -We can type small pieces of Python code into this console, and then simply hit `` to have the CPython interpreter execute our code immediately within the IPython console! +当我们输入简短的Python代码片段并输入回车时,CPython直译器会在IPython命令行中瞬间执行你的代码。 -Let's acquaint ourselves with Python's numbers, strings, and lists. In doing so, we will learn about the Python standard library, and how to make use of its modules, like the math module. IPython's autocompletion and documentation-display utilities will provide a nice means for exploring the library and the functionality built into the different types of Python objects. A quick glimpse at Python's strings and lists will hint at the common interface Python provides for working with sequences of objects, while highlighting some of the nice features of these all-important data types. +让我们熟悉一下Python的数字(number),字符串(string),和列表(list)。在这个过程中,我们会了解Python标准库的一些模组,如math模组。IPython提供的自动完成和说明文档显示功能会帮助我们探索标准库和其中Python对象(object)的功能。尝试使用Python的字符串和列表会帮助我们对Python的通用界面产生印象,并演示这些基本数据类型的方便特征。 -## Dabbling with Numbers -Time to execute some Python code that performs simple arithmetic. Typing `2 + 3` into the IPython console and hitting the `` key, you should see the following input and output in the console: +## 玩玩数字 +是时候执行一些简单算术的Python代码了。在IPython命令行中输入 `2 + 3` 并敲击回车,你应该能看到接下来的输入和输出: ```python 2 + 3 ``` -This console session is persistent, meaning that we can define a variable and then reference it in our code later on within this console session. Let's define the variable `x` and assign it to the integer `10` (please follow along in the IPython console) +这个命令行进程是持久性的,也就是说我们定义的变量可以在这个进程之后的代码重新调用。让我们定义变量 `x` 并向其赋值数值整数 `10`(请在命令行中跟随本教程) ```python x = 10 ``` -We can check the contents of `x` in this console by simply entering `x` in the next line and hitting ``: +我们可以在这个命令行里查看 `x` 的值。在下一行中输入 `x` 并回车: ```python x ``` -Now, let's use `x` in a quadratic equation $x^{2} + 2x + 3$, and compute this total. +现在,让我们在二次方程 $x^{2} + 2x + 3$ 中调用 `x`,并计算结果。 ```python x**2 + 2*x + 3 ``` -Python's "standard library", the various tools and functions that come packaged as part of the core language, includes plenty of familiar mathematical functions. As a matter of organization, Python stores these mathematical functions away in a module named "math". To make use of this math module, we must import it into our code. +Python的“标准库”——也就是和Python核心语言一起包装的各种工具和函数——包含了很多常见的数学函数。为了组织和结构,Python将这些数学函数存在一个叫做“math”的模组里。我们必须要在代码里导入(import)这个模组来使用这些函数。 ```python import math ``` -Having imported it, the term `math` now refers to the math module in our code. IPython provides a nice way for us to see a list of all the functions that are provided by the math module. To utilize this, type into the console `math.` (note the trailing period) and then hit ``. You should see this list appear: +在导入完之后,`math` 这个单词在我们代码里将代表math模组。IPython提供了一个查看math模组所有函数的方便方法。在命令行中输入 `math.`(注意在单词后面的点)并敲击 ``。你应该看到接下来的这个列表: ![Displaying the contents of the math module](attachments/ipython_math.PNG) -In general, hitting `` will cue IPython to try to autocomplete code for you. This menu displays all the valid things that you could type after `math.`. Looking at the functions starting with "s", we see `sqrt()`. This is the square root function. To see autocompletion in action, type `math.sq` and then hit ``. You should see the code autocomplete to `math.sqrt`. +一般来说,敲击 `` 会使IPython尝试自动完成你的代码。这个列表显示了所有可以在 `math.` 之后输入的内容。在“s”打头的函数中,我们可以看到 `sqrt()`。这就是一个求平方根的函数。输入 `math.sq` 然后在敲击 `` ,你会看到IPython将自动完成你的代码成 `math.sqrt`。 -Let's use this function to compute $\sqrt{100}$: +让我们用这个函数来计算 $\sqrt{100}$: ```python math.sqrt(100) ``` -You might wonder why the result displayed as `10.0` and not simply as `10`; in Module 2 we will see that these are two different *types* of numbers in the Python language. The former is called a floating-point number, indicating the presence of its decimal point, whereas the latter is an integer. The `math.sqrt` function is defined such that it always returns its results as floating-point numbers. +你可能会好奇为什么计算的结果显示的是 `10.0` 而非 `10`;在模组2中我们会了解这两个输出是两种不一样的数据*类型*。前者被称为浮点数,因为小数点是一个漂浮的点,而后者则是一个整数。函数 `math.sqrt` 的定义使得它永远都会返回浮点数。 -In the case that we want to make frequent use of a certain function from the math module, it'd be nice to avoid having to type out the math module prefix, `math.`, repeatedly. We can accomplish this by importing an individual function from the math module. Let's import the factorial function from the math module. +当我们想要经常使用math模组里的某个函数时,我们可能希望不需要每次都要打出math模组的前缀 `math.`。我们可以通过从math模组导入单独的函数来达成这个目的。我们将从math模组导入阶乘(factorial)函数。 ```python from math import factorial ``` -We can now make use of the `factorial` function in our code. Recall that 5-factorial is $5! = 5\times 4\times 3\times 2\times 1 = 120$ +我们现在可以在代码里直接调用 `factorial` 函数。5的阶乘是 $5! = 5\times 4\times 3\times 2\times 1 = 120$ ```python factorial(5) ``` -## Messing with Strings -In the context of code, written text is referred to as a string of characters, or string for short. Python is an excellent language for doing text-processing work as it provides many convenient, efficient functions for working with strings. +## 试试字符串 +在代码中,我们将文字理解为一连串的字符,也就是字符串(string)。因为Python提供了很多方便,高效的字符串处理函数,所以它很适合于文本处理工作。 -To begin, we simply form a string by typing characters between quotation marks: +让我们先通过在双引号之间敲击字符来创建第一个字符串吧: ```python "the cat in the hat" ``` -Single quotes also work: +单引号也可以: ```python 'the dog in the sash' ``` -If you use single quotes to form a string, then that string is able to contain the double-quote as a character (and vice versa): +译者注:记得切换到英文输入法的引号 '' 和 "" 。中文的 ‘’ 和 “” 是不会被识别的。 + +如果你使用单引号来创建一个字符串,那么那个字符串就可以含有双引号(反之亦然): ```python 'He picked up the phone, "Hello? What do you want?" Bob was a rather impolite dude.' ``` -There are designated special characters that allow us to affect the way a string is formatted when it is printed to the string. For example, if `\n` ever occurs in a string, it is treated as a single character that indicates a line-break. This will only manifest if such a string is fed to the built-in `print` function, which informs the computer to print text to a user's screen. +当然,我们也有专门的特殊字符来帮助我们改变一个字符串的被打印出时的格式。比如说,如果 `\n` 出现在字符串中,它会被当为一个代表回车的字符。这仅仅会在你使用自带的 `print` 函数(一个指示计算机将文本显示在用户电脑屏幕上的函数)来打印这个字符串时才会显示, -Let's create a string that will display as three separate lines, when printed to the screen. +让我们创建一个会被 `print` 显示为三行文字的字符串。 ```python print("I like to talk to dogs.\nI like to talk to cats.\nWhat's my deal?") ``` -Of course, strings are useful beyond merely containing text! Let's explore some ways to manipulate strings. First, we'll write a string and assign it to a variable named `sentence`: +当然,字符串的作用远远不及仅仅存储文本!让我们探索一些操作字符串的方法。首先,我们将创建一个字符串并将其存储到一个名为 `sentence` 的变量中: ```python sentence = "Who would have thought that we were robots all along?" ``` -Let's see how many characters are in this string by checking the "length" of this sequence of characters: +让我们通过字符串的“length”(长度)来查看这个字符串有几个字符吧: ```python len(sentence) ``` -We can access the first 4 characters in the string, the last 6 characters, or a few characters in the middle by "slicing" the string: +我们可以通过切片(slice)这个字符串来查看它的前四个字符,最后六个字符,或者中间的字符。 ```python sentence[:4] @@ -143,54 +145,54 @@ sentence[-6:] sentence[5:22] ``` -We can also check to see if some other string is contained within our string. Is the string `"robot"` contained within `sentence`? +我们也可以查看是否我们的这个字符串是否包含其它的某个的字符串。字符串 `"robot"` 是否在 `sentence` 中呢(is `"robot"` **in** `sentence`)? ```python "robot" in sentence ``` -As a quick way to check out the built-in functions that strings have available to them, we can make use of IPython's autocompletion feature once again. Type `sentence.` (including the trailing period) and then hit ``. A menu of functions should appear as so: +为了快速查看所有字符串可以调用的自带函数,我们可以再次使用IPython的自动完成功能。输入 `sentence.`(不要漏掉最后的点)并敲击 ``。我们会看到一列表的函数: ![Built-in functions for a string](attachments/ipython_string.PNG) -Let's use the count function to tally the number of lowercase w's in `sentence` +让我们用名为count的函数来数 `sentence` 中有多少小写的w。 ```python sentence.count('w') ``` -Let's see what the replace function does. IPython provides a great utility for looking up the documentation for a function by simply putting two question marks after the function name. For example: +让我们看看replace函数是做什么用的。IPython提供一个很方便的看看函数说明文档的功能,只需在函数名后输入两个问号。如下: ![Looking up documentation for a function](attachments/ipython_doc1.PNG) -Putting our newfound understanding of the string's replace function, let's replace "robot" with "computer": +利用我们刚得到的对字符串replace函数的理解,让我们用“computer”来代替“robot”: ```python sentence.replace("robot", "computer") ``` -## Playing with Lists -A list is one of several types of containers that are built into Python's standard library. It can hold a sequence of Python objects. We can create a list of numbers: +## 看看列表 +列表(list)是Python标准库中容器的一种。它可以存储一序列(sequence)的Python对象(object)。我们可以创建一个数字列表: ```python [-1, 1/3, 10*2, 7-1] ``` -A list can contain any type of Python object; it can store a mix of numbers, strings, other lists, and much more! +列表可以存储任何类型的Python对象;它可以混合存储数字,字符串,其它列表,和任何类型的对象。 ```python [1, 2, "a", 0.5, "apple and orange"] ``` -You can join lists together, which is known as concatenation. +你可以将两个列表粘连(concatenate)到一起。 ```python [1, 2, 3] + ["a", "b", "c"] ``` -Like a string, a list is sequential in nature and we can access the items in a list by specifying its position in the sequence. This is known as "indexing" the list; the index of the first item in a sequence is always 0. +像字符串一样,列表本质上也是一个序列,所以我们可以通过项目在列表中的位置来访问它。这个位置叫做项目的索引(index);序列第一个成员的索引永远都是0. ```python my_list = [10, 20, 30, 40, 50, 60] @@ -204,13 +206,13 @@ my_list[0] my_list[1] ``` -Negative integers can be used to index relative to the end (right-side) of the list. +你可以使用负整数来相对于列表结尾(右边)来索引。 ```python my_list[-1] ``` -You can change an entry in a list by assigning it to a new value. +你也可以通过对列表中的项目赋值来修改列表的内容。 ```python -5 in my_list @@ -228,13 +230,13 @@ my_list -5 in my_list ``` -We can also access multiple items in a list at once by slicing the list, like we did with the string. +我们也同样可以通过切片(slice)这个列表来存取其中的多个项目,就像之前的字符串一样。 ```python my_list[:3] ``` -This slice can be used to update the first three entries of the list +这个切片出的结果可以用来更新列表的前三项内容。 ```python my_list[:3] = "abc" @@ -244,7 +246,7 @@ my_list[:3] = "abc" my_list ``` -To wrap up this quick demo, let's append an new entry to the end of this list. +为这个演示收尾,让我们在这个列表的结尾附加(append)一个新成员。 ```python my_list.append("moo") diff --git a/Python/Module1_GettingStartedWithPython/Installing_Python.md b/Python/Module1_GettingStartedWithPython/Installing_Python.md index a932c0a..f19daf4 100644 --- a/Python/Module1_GettingStartedWithPython/Installing_Python.md +++ b/Python/Module1_GettingStartedWithPython/Installing_Python.md @@ -4,110 +4,100 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Installing Python with Anaconda, Difficulty: Easy, Category: Tutorial :keywords: python, anaconda, instructions, environments, beginner, data science, introduction -``` + -## Installing Python +## 安装Python -Without further adieu, we now provide instructions for installing Python and other useful Python libraries on your machine via the Anaconda platform. Installing the Anaconda platform will install the following: +废话不多说,让我们提供安装Python和其它有用的Python模组的步骤吧。安装Anaconda平台会安装以下的内容: - - Python; specifically the CPython interpreter that we discussed in the previous section. - - A number of useful Python packages, like matplotlib, NumPy, and SciPy. - - Jupyter, which provides an interactive "notebook" environment for prototyping code. - - conda: a package manager that will allow you to install and update Python and additional Python packages, while handling all compatibility issues for you. + - Python;具体来讲是之前一节提到的CPython直译器。 + - 一些有用的Python模组,如matplotlib,NumPy,和SciPy。 + - Jupyter,用以提供用来编写新代码的互动式“记事本”环境。 + - conda:一个帮助你安装并升级Python和其它Python模组以及自动处理兼容性问题的包管理器。 -Note that installing Python via Anaconda will **not** break any other installations of Python that already exist on your computer. See [What did this just do to my computer?](#What-did-this-just-do-to-my-computer?) for more details. +请注意通过Anaconda安装Python**不会**破坏通过其他途径安装的Python。详阅[我刚对我的电脑做了什么?](#我刚对我的电脑做了什么?)。 -Some of the packages provided by Anaconda, like NumPy, have been [optimized](https://docs.anaconda.com/mkl-optimizations/) and will run significantly faster than if you installed them manually. +有些Anaconda提供的模组,如NumPy,是被[优化](https://docs.anaconda.com/mkl-optimizations/)过的,而因此比起单独安装运行得快很多。
-**Takeaway**: +**经验**: -"Anaconda" is a collection of the CPython interpreter and a number of very popular Python libraries for doing data science-related work. It also provides a package manager for downloading/updating Python packages, and an environment manager for maintaining independent installations of Python side-by-side. +“Anaconda”是包含CPython直译器和其它流行Python数据科学模组的集合。它提供一个用来下载和更新Python模组的包管理器,以及一个用以同时维持多个独立Python安装的环境管理器。
-### Installing Anaconda +### 安装Anaconda + +1. 点开[本链接](https://www.anaconda.com/download/),并单击**Python 3**对应的“Download”按钮。 +2. 当下载完成后,安装下载的文件。安装过程中会有个选择:`Add Anaconda to the system PATH environment variable`(将Anaconda加到系统PATH的环境变量中);我建议你**选择**这个选项(懂行的用户:见下以了解关于这个选择的注意事项)。 +3. 完成20分钟的[“Getting Started”](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html)(入门)教程来熟悉 `conda`。这很重要!译者注:这里是英文的文档,有能力的读者可以用谷歌机翻。如果实在看不懂,文章中关于环境管理的内容在本节后面会有包含。 -1. Navigate to [this page](https://www.anaconda.com/download/), and click the "Download" button for **Python 3**. -2. After the download is complete, begin the installation process. There will be an installation option: `Add Anaconda to the system PATH environment variable`; we advise you to **enable** this installation option (advanced users: see below for caveats). -3. Complete the 30 minute ["Getting Started"](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html) tutorial to familiarize yourself with `conda`. This is very important! +你将会需要知道如何打开一个命令行(Windows用户是cmd.exe),以及如何在命令行中切换文件夹。如果你不知道如何做到这些,请阅读一个和你操作系统相对应的教程。译者注:Windows:[文库](https://wenku.baidu.com/view/35c6365c7cd184254a353526.html)(注意要下载券)或[经验](https://jingyan.baidu.com/article/adc815138b23eef722bf7348.html)(不全面,但够用)。 -You will need to know how to open a terminal (cmd.exe for Windows users) on your computer, and how to navigate between directories in the terminal. If you do not know how to do this, read a 'how-to' for whatever operating system you are using. - -### What did this just do to my computer? +### 我刚对我的电脑做了什么? -This created a directory called `Anaconda3` (or some variant of this) on your computer, which contains all of the files associated with the CPython interpreter, all of the modules in Python's standard library, the aforementioned 3rd party packages that come as part of the Anaconda distribution (e.g. NumPy, SciPy, Jupyter, iPython), and the `conda` package manager. It also contains the executable files for all of these applications. The default install location for Anaconda is: +这创建了一个叫做 `Anaconda3`(或类似)的文件夹。它包含了所以和CPython直译器有关的文件,所有Python标准库的模组,之前提到过的Anaconda包含的第三方模组(例,NumPy,SciPy,Jupyter,iPython),和 `conda` 包管理器。它也包含了这些所有的程序的可执行文件。默认的Anaconda安装路径为: -- (Linux): `/home//Anaconda3` -- (Windows): `C:\Users\\Anaconda3` -- (Mac): `/Users//Anaconda3` +- (Linux):`/home//Anaconda3` +- (Windows):`C:\Users\\Anaconda3` +- (Mac):`/Users//Anaconda3` -If you followed the install instructions as specified above, then the Anaconda-installer also *placed this directory in your system's "path"*. Let's briefly discuss what this means. Your system's path is simply a list of directories. Whenever you execute any command in your computer's terminal, the computer will quickly search through the directories that are specified in the path for an executable with that name; *it will execute the first such executable that it finds*. Thus, by placing the `Anaconda3` directory at the beginning of your path, the Anaconda-installer has ensured that your computer will prioritize Anaconda's python executable over any other installations of Python on your computer, because it will find that executable first. +如果你跟随了上文的安装指示,那么Anaconda安装器应该*将这个文件夹输入到了你系统的“path”环境变量中*。让我们快速地描述一下这具体意味着什么。系统的path是一个文件夹列表。每当你从你计算机的命令行中执行任何指令,你的计算机都会快速搜寻“path”包含的文件夹下面同名的可执行文件;*计算机将会执行它找到的第一个同名可执行文件*。因此,将 `Anaconda3` 文件夹放在path列表的最顶端会导致你的系统最优先使用Anaconda的Python可执行文件,而非任何其它安装的Python版本,因为系统会首先找到Anaconda版本的可执行文件。 -For Linux and Mac users, it is very likely that your system already has a version of Python installed. *It is critical that you do not attempt to uninstall, remove, or change this native version of Python*. Those operating systems use their native versions of Python to perform some of their services. Those services are written such that they will directly invoke the Python executable that came with the operating system - they will not accidentally run the version of Python that came with Anaconda. At the end of the day you can simply install Anaconda without worrying about any of these details. +对Linux和Mac用户而说,你的系统很有可能已经安装了某个版本的Python。*千万不要尝试卸载,删除,或修改系统自带的Python*。这些操作系统用它们自带的Python去执行系统的一些服务。这些服务会直接专门调用系统自带的Python可执行文件——它们不会意外地使用Anaconda版本的Python。所以你要知道的就是你可以安装Anaconda而不担心以上这些细节。 -**An important note for people who code in languages other than Python:** Anaconda has its own `lib` and `bin` directories that it uses to store library files and binary files as needed. While this makes it very easy for users to install sophisticated Python packages that leverage C-libraries without having to manually build those libraries, it also means that your system will prioritize Anaconda's files before your system-level files. This can be a big problem if you work in languages other than Python. +**对用其它编程语言写代码的人的重要事项:**Anaconda使用它自己的 `lib` 和 `bin` 文件夹来存储模组文件和二进制文件。虽然这让用户可以简单地安装复杂的使用C库的Python模组,但是这也意味着你的系统会首先使用Anaconda的文件而不是你的系统的 `lib` 和 `bin`。如果你编写其它语言的代码,这可能会是个大问题。 -The simple solution to this is to *not* have the Anaconda-installer include Anaconda in your path. Instead, you can create an alias that will allow you manually prepend Anaconda to your path. E.g., in Linux you can add the following alias to your `~/.bashrc` file: +最简单的解决方案就是*不要*让Anaconda安装器将Anaconda包含在你的path里面。你可以创建一行alias(代名)来手动前置Anaconda到你的path里。比如说,在Linux上你可以在 `~/.bashrc` 文件中添加如下的alias: ```shell alias anaconda="export PATH=/home//anaconda3/bin:$PATH" ``` -With this alias in place, you can simply invoke the command `anaconda` in your terminal to place Anaconda at the beginning of your path for that terminal session. +设置好这个alias后,你可以从命令台调用 `anaconda` 来将Anaconda暂时添加到path的顶端——这只维持到你当前命令台被关闭之前。 -### A Brief Introduction to Conda Environments +### 快速入门Conda环境 -`conda` is not only a package manager, but also a powerful environment manager. Let's take a moment to motivate a common use case for environment management before we dive into what it actually is: +`conda` 不仅仅是一个包管理器,它也同时是一个很强大的环境管理器。在了解它之前,让我们先看看为什么我们会需要一个环境管理器: ->It is expected and encouraged that you work through Python Like You Mean It using the latest version of Python (Python 3.X). That being said, it is not uncommon to encounter courses and projects that require you to use Python 2.7, which is a dead version of the language. Is there a simple and sane way to switch back and forth between working in Python 3 and Python 2.7 environments? Yes! Utilizing conda environments is a perfect way to solve this problem. +>PLYMI建议你使用最新版本的Python(Python 3.X)来阅读本资源。但是,很多时候其它的课程或项目会需要你使用Python 2.7,一个已经不被更新或维护的Python版本。有没有一个简单干净的方法来快速在Python 3和Python2.7环境中切换呢?有!使用conda环境可以完美解决这个问题。 -Assuming that your initial installation of Anaconda contained Python 3, then your *root* (i.e. default) conda environment is that Python 3 environment. You can now create a conda environment that instead includes Python 2.7 and all of the 3rd party packages that come with Anaconda. Execute the following command in your terminal: +假设你的Anaconda安装包含了Python 3,那你的*root*(默认)conda环境就是这个Python 3环境。你现在可以创建一个包含Python 2.7和所有Anaconda自带的第三方模组的conda环境。在你的命令行中执行以下指令: ```shell conda create -n py27 python=2.7 anaconda ``` -Once the installation process is complete, you will be able to activate this environment, which we have named `py27`, by executing the command (Linux, Mac): -```shell -source activate py27 -``` -in your terminal. If you are in Windows, the command is: +当安装成功后,你将可以激活(activate)这个叫做 `py27` 的环境。在命令行中执行以下命令: ```shell -activate py27 +conda activate py27 ``` -Activating an environment simply updates your system's path, swapping the directory `Anaconda3` with `Anaconda3/envs/py27` in this instance. Thus your system will now find the Python 2.7 executable and its associated libraries in its path. Note that this path change only occurs effect in *that particular terminal session*. Any other terminal session will default to the root conda environment. -Having activated your `py27` environment, you can start a vanilla Python console, an iPython console, a Jupyter notebook, run a Python script, etc. These will now all use Python 2.7. You can also use `conda` (and `pip`) to install Python 2.7-compatible packages in this environment. As long as your path points to `Anaconda3/envs/py27` and not `Anaconda3`, it is as if this is the only version of Python that lives on your computer. +激活一个环境仅仅会更新你的系统path变量。在本例中这意味着 `Anaconda3` 会被更新为 `Anacond3/envs/py27`。这样你的系统就会在path中找到Python 2.7的可执行文件还有该版本相对应的模组。请注意这个变化仅仅作用于**当前的命令行进程**。任何其它的命令行进程都会默认使用叫做root的conda环境。 -Deactivating this environment will return you to the root Python 3 environment. That is, it will switch your path back to including `Anaconda3` instead of `Anaconda3/envs/py27`. Simply invoke the command (Mac, Linux): - -```shell -source deactivate -``` +当你激活名为 `py27` 的环境后,你可以使用Python命令行,iPython命令行,Jupyter记事本,执行Python脚本,等等。这些现在都会使用Python 2.7。你可以用 `conda`(和 `pip`)来在这个环境中安装和Python2.7兼容的模组。只要你的path指向的是 `Anaconda3/envs/py27` 而不是 `Anaconda3`,这些指令的行为就会如同Python 2.7是计算机上唯一的Python版本一般。 -On Windows, the command is: +冻结(`deactivate`)这个环境将将你返回到名为root的Python 3环境。这意味着conda将重新修改path,让它包含 `Anaconda3` 而不是 `Anaconda3/envs/py27`。执行以下指令: ```shell -deactivate +conda deactivate ``` -And like that, conda environments give you all of the powers of a necromancer, allowing you to nimbly cross back and forth between the land of the living (Python 3) and the dead (Python 2.7). +就这样,conda环境提供给你像招魂师一样的能力,轻便地在活的(Python 3)和死的(Python 2.7)之间切换。 -Conda environments have more uses than simply switching back and forth between Python 3 and 2. Many people like to make a new conda environment for every major project that they work on, so that they can freely install any dependencies that are needed for that particular project, without worrying about conflicts with their other work. You should be keen on making regular use of conda environments. +除了在Python 3和2之间切换,conda环境有着很多其它的作用。很多人喜欢为每一个新的大规模项目创建一个新的conda环境。这样他们可以随意安装任何该项目需要的模组而不用担心和其他项目模组的冲突。读者应当注意学习和使用conda环境。 -It is highly recommended that you take time to read through [this tutorial on managing conda environments](https://conda.io/docs/user-guide/tasks/manage-environments.html). - +我非常建议你去阅读[这个管理conda环境的教程](https://conda.io/docs/user-guide/tasks/manage-environments.html)。译者注:同样是英文的文档,可以考虑不看。 diff --git a/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md b/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md index 9b63e96..915be5f 100644 --- a/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md +++ b/Python/Module1_GettingStartedWithPython/Jupyter_Notebooks.md @@ -4,92 +4,99 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Jupyter notebooks, Difficulty: Easy, Category: Tutorial - :keywords: jupyter, notebook, kernel, basics, server, console, command line, plot, beginner, data science -``` + :keywords: jupyter, jupyter lab, notebook, kernel, basics, server, console, plot, beginner, data science + + +# Jupyter记事本 +近年来,Jupyter Notebook(记事本)成为了一个极其流行的帮助用户使用Python和其它语言做实验的工具。它的流行代表着数据科学实验形式的转变。 + +Jupyter记事本类似于IPython命令行,但,相比起IPython每次编写运行一行代码的形式,你可以轻松地编辑和重新执行*任何*在记事本中的代码。同时,你可以保存一个记事本,然后在未来去运行和修改它。Jupyter记事本提供很多特别实用的功能。比如说,你可以在记事本中嵌入可视化的多媒体(如表格和图画)并利用[Markdown语法](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)编写方便美观的文本来演示和解释记事本的内容。 -# Jupyter Notebooks -In recent years, the Jupyter Notebook has become a massively popular tool for doing research-oriented work in Python and other languages alike. Its emergence marked a paradigm shift in the way data science is conducted. +通过以上这些方式,Jupyter记事本成为了一个出众的实际应用工具。比如说,你可以在一个记事本上跟随本文的流程,边读边运行本文的代码片段和回答阅读理解问题,并同时使用Markdown标题来视觉上区分记事本的不同区块。当我做研究时,我经常创建Jupyter记事本以编写代码来分析数据,绘制各种实验结果的图表,并撰写详细的Markdown文本来记录我的工作。最后产生的成果是一个我可以分享给我同事的记事本。我可以在几个月后重新打开这个记事本而不会不记得我之前都做了些什么。 -A Jupyter notebook is similar to the IPython console, but, instead of only being able to work with a single line of code at a time, you can easily edit and re-execute *any* code that had been written in a notebook. Furthermore, you can save a notebook, and thus return to it later. Additionally, a notebook provides many terrific features. For instance, you can embed visualizations of data within a notebook, and write blocks of nicely-formatted text (using the [Markdown syntax](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)), for presenting and explaining the contents of the notebook. +## JupyterLab -In this way, the Jupyter Notebook stands out as an excellent tool for many practical applications. You could work on a notebook while you are working through sections of this website, for instance, testing out snippets of code, and answering reading-comprehension questions as you proceed through the text, and using markdown-headers to visually separate different portions of the notebook. When I do research, I am always creating Jupyter notebooks in which I write code that analyzes data, I plot various results, presented in different ways, and I write detailed markdown-text blocks to document my work. The end result is something that I can share with my labmates, and easily revisit months later without having to struggle to recall what I had done. +[JupyterLab](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)是由Project Jupyter团队开发的一个全新的网页端交互界面。通过它,你可以在你的浏览器中编辑并运行Jupyter记事本,命令行,和文本编辑器。除了各种功能和相比Jupyter记事本更加成熟的用户界面之外,JupyterLab还提供了可以用来显示数据,图片,和代码输出的在Jupyter记事本之外的可移动窗口。这将允许你高效地进行数据科学工作。 -Enough gushing about Jupyter notebooks. Let's start using them! +本文在这里推荐你阅读[JupyterLab说明文档](https://jupyterlab.readthedocs.io/en/stable/getting_started/overview.html)来了解它提供的额外功能。 +下文将针对Jupyter记事本来进行讨论,但是运行JupyterLab服务器和操作其中的记事本的方法和Jupyter记事本基本完全一样。Jupyter记事本和JupyterLab都可以[用Anaconda安装](https://cn.pythonlikeyoumeanit.com/Module1_GettingStartedWithPython/Installing_Python.html)。 -## Running a Notebook Server & Creating a Notebook -In your terminal, navigate to a directory (a.k.a folder) that you are okay creating files in. If you don't know how to do this, Google it! +## 运行记事本服务器并创建记事本 +废话不多说,让我们来使用Jupyter记事本吧! -Once you are in the desired directory, execute in your terminal (type the following, and then hit ``): `jupyter notebook` +在你的命令行中,导航到随便一个你愿意创建文件的文件夹。如果你不知道怎么做,上网搜一下! -You should see some text appear in your terminal: +当你的命令行在你想要的文件夹内后,运行(键入以下内容然后回车):`jupyter notebook` + +你应该会看到以下的内容出现在你的命令行中: ![Starting a jupyter notebook server on your machine](attachments/jupyter_login.PNG) -This is a "notebook server" that is running on your machine - it basically handles all of the communication between your browser and your machine. A new window or tab should open in your web browser, which looks like a file explorer. +这是一个在你机器上运行的“记事本服务器”——它将会处理所有在你浏览器和机器之间的交互。一个看起来像文件夹浏览器的窗口应该会在你的浏览器中打开。 ![File explorer that opens in your browser](attachments/jp_files.PNG) -You can use this to enter subdirectories and to open up any Jupyter notebooks that you have saved. *You will need to use this file explorer any time that you want to open up a Jupyter notebook, old or new.* In the top-right corner of this window, click on the dropdown menu labeled "New", and select the option `Python 3`. +你可以利用这个界面进入子文件夹并打开任何已经存储的Jupyter记事本。*不管是新是旧,每次你想要打开一个Jupyter记事本时你都需要使用这个文件夹浏览窗口。*在窗口右上角,你可以点击展开菜单“New”并选择选项 `Python 3`。 ![](attachments/jp_dropdown.PNG) -A new tab will open in your browser, revealing a "Jupyter notebook" called `Untitled.ipynb` running a Python 3 kernel. Clicking `File > Rename` in the notebook will enable you to name your notebook. `.ipynb` is the file-type suffix used for Jupyter notebooks (`ipynb` stands for "IPython-notebook", which is what these notebooks were called prior to 2014). The commands that you run in this notebook are interpreted and executed by Python in the essentially same way that they would be in a IPython console. +你的浏览器会打开一个新的窗口并显示一个名为 `Untitled.ipynb` 的运行Python 3壳的Jupyter文件夹。点击 `File > Rename` (文件 > 重命名)会允许你修改记事本的名字。`.ipynb` 则是Jupyter记事本的文件类型后缀(`ipynb` 代表着 "IPython-notebook",也就是这些Jupyter记事本在2014年前的名字)。在这个记事本中运行的命令会被Python像IPython命令输入行一样直译并执行。
-**Jupyter Notebooks Do Not Use the Internet**: +**Jupyter记事本并不使用互联网**: -Although a Jupyter notebook opens in your browser, *everything is happening locally on your machine*. You don't need to be connected to the internet to work on a Jupyter notebook! The notebook server that you ran in your terminal is simply routing communication from your browser to your local machine. For instance, it is sending code to your CPython interpreter to be executed. +虽然Jupyter记事本在你的浏览器中打开,*所有的东西都是在本地机器上发生的*。你不需要连接互联网来使用Jupyter记事本!在命令行中运行的记事本服务器仅仅管理浏览器和本地机器的交互。比如说,它会将代码发送到你的CPython直译器去运行。
-## Notebook Cells -Whereas a Python console only allows you to work on one line of code at a time, a notebook allows you to write code within "cells" and to execute these chunks of code cell-by-cell. In the first cell, write the lines of code: +## 记事本小节 +在Python命令行中,你每次只能编写一行代码;但一个记事本让你可以以小节(cell)为单位来编写和运行代码。在你的记事本的第一小节中,输入以下代码: ```python x = 3 y = 4 ``` -then press `+`. This will execute all of the code within the given cell (in this instance, assigning the variables `x` and `y` with the values 3 and 4, respectively) and then creates a new cell below. In the next cell type the code: +然后敲击 `+`。这会运行这个小节里的所有代码(在这个例子中,这会分别给 `x` 和 `y` 赋值 3 和 4)并在下面创建一个新的小姐。在新的小节中输入以下代码: ```python x + y ``` -and hit `+` to execute this code. The number 7 will appear beneath the cell - this, of course, is the value that is returned when `3 + 4` is evaluated: +敲击 `+` 以运行此代码。小节下面会显示数字 7——也就是运行 `3 + 4` 的结果: ![jupyter notebook example](attachments/jupyter_early.png) -Notice that the notebook "knows" about its variables across its cells. This doesn't just work from top to bottom - you can define `z = 2` in the third cell, and then execute code that references `z` in the first cell. What really matters is the *order* in which the cells are executed. Notice that `In[1]` denotes that the top cell with the first input-cell executed in the notebook, and `In[2]` denotes the second cell that was executed. +请注意,记事本“知道”在不同小节中的变量。这不仅仅在从上到下时适用——你可以在第三小节定义 `z = 2`,然后在第一小节运行调用 `z` 的代码。唯一需要注意的是运行这些小节的*顺序*。注意 `In[1]` 代表这个小节是第一个在这个记事本中被执行过的小节,而 `In[2]` 代表着第二个被执行过的小节。 -Formally, the cells within a given notebook share a common "namespace": any variable defined in a cell can be referenced or redefined in any other cell within the notebook. On the other hand, separate notebooks are completely independent from one another. You can be working on multiple notebooks at once, and they will never "know" about one another. +正式来讲,在一个记事本中的所有小节共享同一个“命名空间”(namespace):在任何一个小节中定义的变量可以在任何其它相同记事本的小节中调用或重新定义,但但不同的记事本的命名空间互相完全独立。也就是说你可以同时编写多个记事本,而它们永远也不会“知道”互相的存在。 -A major value of using a notebook is that you can rapidly edit these cells (say, change `x = 3` to `x = 10`), and re-execute them to nimbly tinker with whatever code you are developing. Although simple, this is a hugely powerful environment for prototyping code. +使用记事本的一大好处是你可以快速地修改这些小节(比如将 `x = 3` 改成 `x = 10`)并重新执行它们来尝试你正在编写的新代码。这是一个简单却极其强大的编写新代码的环境。 -## An Example Notebook -To show off a more exciting use-case, let's create a notebook that plots some data for us. We'll use matplotlib, a Python library that is used for plotting data, and NumPy, the premiere library for doing numerical work in Python. We will import these libraries for use in our code. Next we'll define some mathematical functions. And finally, we'll plot these functions evaluated on a large number of closely-spaced points on the domain. +## 样例记事本 +为了演示一个更加有趣的记事本使用情景,让我们创建记事本来绘制一些数据图。我们将使用matplotlib,一个用于绘制数据的Python模组,和NumPy,旗舰的数字工作Python模组。我们将导入这些模组。然后,我们将定义一些数学函数。最后,我们将绘制这些函数在大量数值上的解。 ```python import numpy as np import matplotlib.pyplot as plt -# this tells Jupyter to embed matplotlib plots in the notebook +# 这会告诉Jupyter将matplotlib的图表嵌入在记事本中 %matplotlib notebook ``` @@ -98,19 +105,19 @@ def sinc(x): return np.sin(x) / x def d_sinc(x): - "derivative of sinc-function" + "sinc函数的导数" return np.cos(x)/x - np.sin(x)/x**2 ``` ```python -# evaluate functions at 1000 points evenly spaced in [-15, 15] +# 用1000个平均分布在[-15, 15]之间的点求值 x = np.linspace(-15, 15, 1000) f = sinc(x) df = d_sinc(x) ``` ```python -# plot the sinc-function and its derivative +# 绘制sinc函数和它的导数 fig, ax = plt.subplots() ax.plot(x, f, color="red", label=r"$sinc(x)$") ax.plot(x, df, color="blue", ls="--", label=r"$\frac{d(sinc(x))}{dx}$") @@ -123,48 +130,47 @@ ax.grid(True) ax.legend(); ``` -Notice that this notebook interface is great for making adjustments to this plot. You can easily change the color or line-style of the plot and redraw it without having to recompute the functions. You simply re-execute the cell containing the plot code. This is especially nice when the numerical computations required to generate the curves are costly. +注意这个记事本界面很方便对图表做修改。你可以轻松地修改图表的颜色或线条风格并重新绘制,而不需要重新计算这些函数的解。你可以直接重新执行含有绘图代码的小节。这在计算要绘图的数据很昂贵时极其有用。 -## Familiarizing Yourself with Jupyter Notebooks -Here, we will review some essential keyboard shortcuts and notebook features, which will enable you to use notebooks competently. A notebook has two modes of operation: +## 熟悉Jupyter记事本 +在这一段,我们会列出常用的键盘快捷键和记事本功能来帮助你有效地使用记事本。一个记事本有两种不同的模式: -**Command Mode (Press** `` **to activate)** +**命令模式 (敲击** `` **来激活)** -When in command mode, you can use keyboard shortcuts to create/delete/cut/paste notebook cells, and to change a cell's type between code and markdown modes. Your selected cell will be surrounded by a *blue* border when you are in command mode. For a complete listing of keyboard shortcuts, toward the top of the notebook click `Help > Keyboard Shortcuts`. The most critical shortcuts are: +在命令模式中,你可以使用键盘快捷键来创建/删除/剪接/粘贴记事本小节或更改小节的类型(如代码或Markdown)。当你在命令模式中,你选择的小节会有一个*蓝色*的边框。你可以点击记事本上方的 `Help > Keyboard Shortcuts` (帮助 > 键盘快捷键)来查看所有的快捷键。最重要的快捷键是: -- create a new cell above the current cell: `a` -- create a new cell below the current cell: `b` -- delete the current cell: `dd` -- restart the notebook kernel (kill all executions and erase all defined variables): `00` -- change the current cell's type to "Code": `y` -- change the current cell's type to "Markdown": `m` +- 在当前小节上方创建一个新的小节:`a` +- 在当前小节下方创建一个新的小节:`b` +- 删除当前小节:`dd` +- 重启记事本壳(杀死所有进程并删除所有定义的变量):`00` +- 将当前小节的类型改为“代码”:`y` +- 将当前小节的类型改为“Markdown”:`m` -**Edit Mode (Press** `` **to activate)** +**编辑模式(敲击** `` **来激活)** -Edit mode simply permits you to type text into the selected cell. When in edit mode, the current cell will be surrounded by a *green* border. There are two commands for executing a cell: +编辑模式允许你去在选择的小节中输入文本。在编辑模式中,当前选择的小节会有一个*绿色*边框。记事本提供两个执行小节的命令: -- execute current cell: `+` -- execute current cell and then create a new cell below: `+` +- 执行当前小节:`+` +- 执行当前小节并在下方创建新小节:`+` -By default, a cell will be a code-type cell, meaning that its content will be formatted and executed as Python code. Just as you saw when using the IPython notebook, `` can be used to perform autocomplete. Additionally, when your cursor is on the name of a Python function in your code, `+` will bring up a small window with the function's documentations string. This is *very* useful. +小节在创建时默认为代码小节,意味着它的内容会被当作Python代码格式化和执行。就如IPython命令台一样,`` 可以用来自动完成代码。同时,当你的光标在代码中某个Python函数名字上方时,`+` 将打开一个包含该函数的说明字符串的小窗口。这将*很*有用。 ![Looking up code documentation in a notebook](attachments/jp_docstring.PNG) -### Markdown Cells -When a cell is set to Markdown type, its content will not be interpreted as Python code. Instead, its contents will be rendered as stylized text. Refer to [this page](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) as a reference for various markdown stylings. Using markdown cells allows you to create section and subsection headers for your notebook, you can [render LaTeX math equations](http://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations), embed images and videos in your notebook, and much more. In fact, every page in this website was created using Jupyter notebooks! Markdown-type cells are tremendously useful for creating high-quality, well-documented Jupyter notebooks. These are perfect for lab-report assignments. +### Markdown小节 +当一个小节被设置为Markdown类型时,它的内容不会被当成Python代码,反而会被渲染成风格化的文本。参考[此页](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)来学习如何使用不同的Markdown语法。使用Markdown小节会允许你在记事本中创建章节和字章节标题。你可以[渲染LaTeX数学公式](http://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html#LaTeX-equations),在记事本中嵌入照片和视屏,以及更多。事实上,这个网站的每一页都是用Jupyter记事本创建的!Markdown类型的小节对创建高质量,详细记录的Jupyter文件夹极其有用。它们可以完美应对实验汇报类的作业。
-**Be Aware of Cell-Type**: +**注意小节类型**: -If you ever find that your Python code isn't being formatted properly, and doesn't run at all when you execute the cell (you get no output, not even errors), there is a good chance that you have accidentally set the cell to be a 'Markdown'-type cell! Change the cell back to code-type by entering command mode (``) and pressing `y`. +如果你发现你的Python代码没有被正确地格式化,且在执行小节时根本不运行(你看不到任何输入或者错误),那很有可能你一不小心将小节设置为了Markdown类型!进入命令模式(``)并敲击 `y` 以将小节改回代码类型。
- -### Using Jupyter Notebooks with Other Languages -The Jupyter Notebook does not work exclusively with Python. A "kernel" can be developed in order to provide support for a given programming language in Jupyter. Indeed, kernels for several prominent programming languages are being developed for use with Jupyter: +### 将Jupyter记事本用于其它语言 +Jupyter记事本不只支持Python。你可以在Jupyter中为任何编程语言开发一个“壳”(Kernel)。其实很多重要的编程语言都有着自己相对应的壳: - [R](https://github.com/IRkernel/IRkernel) - [Julia](https://github.com/JuliaLang/IJulia.jl) @@ -173,5 +179,7 @@ The Jupyter Notebook does not work exclusively with Python. A "kernel" can be de - [Haskell](https://github.com/gibiansky/IHaskell) - [Go](https://github.com/gopherdata/gophernotes) -The ever-growing list of available kernels for use with Jupyter can be found [here](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels). It should be noted that these efforts are not all equally mature. For instance, whereas the Python and Julia kernels are robust, the Haskell kernel cannot run natively on Windows machines, and the C++ kernel is still in early development, as of writing this. +这时刻增长的可用Jupyter壳列表在[这里](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels)列出。请注意并不是所有的这些项目都很成熟。比如说,虽然Python和Julia的壳都比较强健,Haskell的壳不能在Windows机器上本地化运行,而C++的壳在编写本文时还在前期开发中。 +### Visual Studio Code的Jupyter记事本支持 +Visual Studio Code在近期[开始官方支持Jupyter记事本](https://devblogs.microsoft.com/python/announcing-support-for-native-editing-of-jupyter-notebooks-in-vs-code/)。这意味着你可以在[Visual Studio Code IDE](https://cn.pythonlikeyoumeanit.com/Module1_GettingStartedWithPython/Getting_Started_With_IDEs_and_Notebooks.html)中直接编辑Jupyter记事本,并可以享受如代码完成,调试,和查看变量的额外功能。 \ No newline at end of file diff --git a/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md b/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md index 5ec2450..b98fb0a 100644 --- a/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md +++ b/Python/Module1_GettingStartedWithPython/Numerical_Work_In_Python.md @@ -4,8 +4,8 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python diff --git a/Python/Module1_GettingStartedWithPython/SiteFormatting.md b/Python/Module1_GettingStartedWithPython/SiteFormatting.md index f5f71a4..bdaadb3 100644 --- a/Python/Module1_GettingStartedWithPython/SiteFormatting.md +++ b/Python/Module1_GettingStartedWithPython/SiteFormatting.md @@ -4,67 +4,68 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Overview of formatting in Python Like You Mean It, Difficulty: Easy, Category: Instructions :keywords: overview, formatting, background, code block, console style -``` + -# A Quick Guide to Formatting -This section provides a brief overview of the code formatting style that will be used throughout this text. You are not expected to understand the details of the code, here. This merely provides a guide for what is to come. +# 代码格式的简单指南 +本节将快速介绍本文将采用的代码格式和风格。你暂时不需要理解这些代码的具体细节。这个指南仅仅是为了让你了解接下来的内容的样貌。 -Any code that is included in-line within plain text will be formatted distinctly as so: "the variable `x` was updated...". Such items will be distinguished with backticks wherever such formatting is not available. Take for example the following commented line within Python code: +任何嵌入在正文中的代码都会遵循如此格式:“变量 `x` 被更新...”。当这种格式不可用时,这类小代码片段会被两个反引号围绕。如下: ```python -# the variable `x` will be updated +# 变量 `x` 将被更新 ``` -Python code will be displayed within distinct, colorized code blocks. These will typically begin with a comment, which is meant to serve as a caption that summarizes the purpose of the code block: +长篇的Python代码则会存在于专门的彩色代码块中。这些代码块一般会由一行总结代码块作用的注解打头: ```python -# demonstrating a basic for-loop +# 演示基本的for循环 cnt = 0 for i in range(10): cnt += 1 -#`cnt` is now 10 +# `cnt` 现在是10 ``` -The symbol `>>>` appears within code blocks to indicate "console-style" code, which distinguishes between code being entered by a user and the resulting output. The purpose of this is that it allows us to easily display the result of a computation without having to rely on calling the `print` function. For instance, the following code assigns the integer `1` to the variable `x`, and then displays the result of `x + 2`: +符号 `>>>` 出现于“命令行风格”的代码中,用于区分用户输入的代码和命令行的输出。这类代码块的可以帮助我们轻松地显示计算结果,而不需要老是调用 `print` 函数。比如说,接下来的代码将设定变量 `x` 为整数 `1`,然后显示 `x + 2` 的结果: ```python -# demonstrating the distinction of -# input and output via >>> +# 通过 >>> 演示输入和输出的不同格式 >>> x = 1 >>> x + 2 3 ``` -The code blocks throughout a given section of the text should be understood to be persistent even if there is a mix of "pure" code blocks and "console-style" code blocks. For example, a function may be defined at the beginning of a section, and then referenced throughout the rest of that section: +译者注:命令行在这里泛指各大平台上的类似Windows命令行的程序——你可能会叫它们Git Bash,Terminal,命令行,Shell,Kernel,等等。全文将用“命令台”一词来指代这种程序。 + +不管是“纯粹”的代码块还是“命令行风格”的代码块,请在章节内认为它们的效应是持久化的。比如说,在某一节开始定义的函数完全在这一节后面被调用: ```python -# defining an example function +# 定义一个范例函数 def my_func(x): return x**2 ``` -We can spend some time talking about `my_func` and then see it in action: +我们可以花些时间讨论 `my_func` 并调用它: ```python -# demonstrating `my_func` +# 演示 `my_func` >>> my_func(10.) 100. ``` -Lastly, the input and output of an iPython console and a Jupyter notebook alike is displayed as follows: +最后,iPython命令台和Jupyter记事本的输入和输出都像如下显示: ```python diff --git a/Python/Module2_EssentialsOfPython/Basic_Objects.md b/Python/Module2_EssentialsOfPython/Basic_Objects.md index 486a285..ca7d291 100644 --- a/Python/Module2_EssentialsOfPython/Basic_Objects.md +++ b/Python/Module2_EssentialsOfPython/Basic_Objects.md @@ -4,105 +4,105 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Basics of Python Objects, Difficulty: Easy, Category: Section :keywords: integers, booleans, floats, floating point precision, lists, strings, fundamentals -``` + -# Basic Object Types +# 基本对象类型
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-You will see the term "object" be used frequently throughout this text. In Python, the term "object" is quite the catch-all; including numbers, strings of characters, lists, functions - a Python object is essentially anything that you can assign to a variable. That being said, there are different *types* of objects: Python treats integers as a different *type* of object than a string, for instance. +本文会经常使用“对象”这一单词。在Python中,“对象”包含了很多东西:数字,字符串,列表,函数,等等。简单来讲,一个Python对象是任何可以赋值给变量的东西。尽管如此,对象是分*类型*(type)的:比如说在Python眼中,整数(integer)和字符串(string)的*类型*是不一样的。 -The different object types have manifestly different purposes and thus have different built-in functions available to them. Here, we will review some of the basic types that are built into Python, as a natural entry point to writing code. We will cover: +不同类型的对象为了不同目的而存在,而因此也有着不同的内置函数。在这里,我们将复习Python自带的一些基本类型并以此写一些代码。我们将会讨论: -- numbers (integers, floating-point numbers, and complex numbers) -- booleans -- the "null" type -- strings -- lists +- 数字(整数,浮点数,复数)(number(integer,float-point number,complex number)) +- 布尔值(真或否)(boolean) +- “空”值类(the "null" type) +- 字符串(string) +- 列表(list) -The built-in function `isinstance` will allow us to check if an object is of a given type. You can also use the built-in `type` function to check an object's type. For example, the following code checks if an object is an integer: +Python自带的 `isinstance` 函数允许我们检测对象是否为某一类型。你也可以用自带的 `type` 函数来查看对象的类型。比如说,下面的代码会检测一个对象是否是整数: ```python -# assign the variable `x` to the integer 1 +# 对变量 `x` 赋值整数 1 >>> x = 1 -# checking the type of `x` +# 查看 `x` 的类型 >>> type(x) int -# verifying that `x` is an integer-type object +# 检测 `x` 是否是整数类(integer) >>> isinstance(x, int) True ``` -In a later module, you will learn "object-oriented" programming, which will allow you to create your own, customized objects! +在之后的模组中,你将学习“面对对象”的编程模式。这将允许你创建你自己的定制对象种类! -## Number Types -Python has three basic types of numbers: integers, "floating-point" numbers, and complex numbers. Familiar mathematical symbols can be used to perform arithmetic on all of these numbers (comparison operators like "greater than" are not defined for complex numbers): - -| Operation | Description | -| ------------- |:-------------:| -| `x + y` | Sum of two numbers | -| `x - y` | Difference of two numbers | -| `x * y` | Product of two numbers | -| `x / y` | Quotient of two numbers | -| `x // y` | Quotient of two numbers, returned as an integer | -| `x % y` | `x` "modulo": `y`: The remainder of `x / y` | -| `x ** y` | `x` raised to the power `y` | -| `-x` | A negated number | -| `abs(x)` | The absolute value of a number | -| `x == y` | Check if two numbers have the same value | -| `x != y` | Check if two numbers have different values | -| `x > y` | Check if `x` is greater than `y` | -| `x >= y` | Check if `x` is greater than or equal to `y` | -| `x < y` | Check if `x` is less than `y` | -| `x <= y` | Check if `x` is less than or equal to `y` | - -These operations obey the familiar order of operations from your mathematics class, with parentheses available for association: - -```python -# multiplication takes precedence over addition +## 数字类型 +Python有三种基本的数字类型:整数(integer),浮点数(floating-point number),和复数(complex number)。你可以使用你熟悉的数学运算符来对这三种数字进行算术操作(像“大于”这种比较性的运算符没有定义如何处理复数): + +| 操作 | 描述 | +| ---- |:----:| +| `x + y` | 求两数相加的结果 | +| `x - y` | 求两数相减的结果 | +| `x * y` | 求两数相乘的结果 | +| `x / y` | 求两数相除的结果 | +| `x // y` | 求两数相除的整数商 | +| `x % y` | 求两数的模(`x` modulo: `y`,也就是 `x / y` 的余数)| +| `x ** y` | 求 `x` 的幂 `y` | +| `-x` | 求负数 | +| `abs(x)` | 求数的绝对值 | +| `x == y` | 检测两数是否等值 | +| `x != y` | 检测两数是否不等值 | +| `x > y` | 检测 `x` 是否大于 `y` | +| `x >= y` | 检测 `x` 是否大于或等于 `y` | +| `x < y` | 检测 `x` 是否小于 `y` | +| `x <= y` | 检测 `x` 是否小于或等于 `y` | + +这些运算符和你平时在数学课上见到的运算顺序一样,在没有括号的情况下遵循先乘除后加减。 + +```python +# 先乘除后加减 >>> 1 + 2 * 3 7 -# grouping operations with parentheses +# 用括号更改运算顺序 >>> (1 + 2) * 3 9 -# finding the remainder of division +# 求余数 >>> 11 % 5 1 -# checking an inequality +# 检测不等式是否成立 >>> (2 ** 3) < (2 ** 4) True ``` -It should be noted that in many other programming languages, including the out-dated Python 2, dividing two integers would always return an integer - even if mathematically the result should be a fraction. In Python 3, *the quotient of two integers will always return a floating-point number* (i.e. a number that includes a decimal point): +请注意:在很多其他的编程语言中(包括Python 2),两个整数相除永远都会返回一个整数——就算数学上的结果应该是个分数。在Python 3中,*两个整数相除永远都会返回一个浮点数*(一个包含小数点的数字): ```python -# In many other languages, 3 / 2 returns the integer 1. -# In Python 3, division always returns a floating-point number: +# 在很多别的语言中,3 / 2 会返回整数 1 +# 在Python 3中,除法返回一个浮点数 >>> 3 / 2 1.5 @@ -110,10 +110,10 @@ It should be noted that in many other programming languages, including the out-d 2.0 ``` -The `//` operator is known as the "floor-divide" operator: it performs division between two numbers and returns the result as an integer by discarding any decimal-places for that number (thus returning the "floor" of that number). This can be used to perform the integer-division traditionally used in other programming languages: +运算符 `//` 英文叫做“floor-divide”(直译“地板除”):它取两数相除之后去尾(去掉浮点数小数点后的数字)得到的整数(因为浮点数取整可以往上入——4.5入到5——或者往下舍——4.5舍到4——,所以去尾被称为地板除)。这可以用来进行很多其他语言中传统的整数相除: ```python -# floor-division +# “地板除“ >>> 1 // 3 # 0.3333.. -> 0 0 >>> 3 // 2 # 1.5 -> 1 @@ -123,14 +123,14 @@ The `//` operator is known as the "floor-divide" operator: it performs division
-**Reading Comprehension: Understanding the modulo operator** +**阅读理解:理解模运算符** -The modulo operator, `%`, is not commonly seen in mathematics textbooks. It is, however, a very useful operation to have at our disposal. `x % y` (said as x "mod" y in programmer's jargon) returns the *remainder* of `x / y`. For example: +模运算符 `%` 在数学教材中并不常见。但是它在我们手中是很有用的一个运算符。`x % y` (读作 x “模”(mod)y)返回 `x / y` 的余数。比如说: -- $\frac{3}{2} = 1 + \frac{1}{2}$. 2 "goes into" 3 one time, leaving a remainder of 1. Thus `3 % 2` returns `1` -- $\frac{9}{3} = 3$. 3 "goes into" 9 three times, and leaves no remainder. Thus `9 % 3` returns `0` +- $\frac{3}{2} = 1 + \frac{1}{2}$. 3 中可以去除一个 2,最后余下 1,所以 `3 % 2` 返回 `1` +- $\frac{9}{3} = 3$. 9 中可以去除三个 3,什么都不余下。所以 `9 % 3` 返回 `0` -Given this description of the "mod" operator, simplify the following by hand, and then use the IPython console to check your work: +根据以上对模运算符的解释,先自己猜测下方表达式的结果,并用IPython命令行检查你的答案: 1. `1 % 5` 2. `2 % 5` @@ -141,22 +141,21 @@ Given this description of the "mod" operator, simplify the following by hand, an 7. `22 % 5` 6. `22 % 6` -Now, given any integer, `n`, what are the possible values that `n % 2` can return? See if you can come up with a simple rule for explaining the behavior of `n % 2`. +假设 `n` 是任何整数,`n % 2` 可能返回哪些数值?尝试简明地解释 `n % 2` 的行为。
-### Python's math module -The standard library's math module provides us with many more mathematical functions, like logarithms and trigonometric functions. A complete listing of them [can be found in the official Python documentation](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions). This module must be imported into your code in order to use its functions: +### Python的math模组 +标准库的math模组为我们提供更多的数学函数,像对数(logarithm)和三角函数。完整的列表[可以在Python官网上找到](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions)。要使用math模组里的函数,你必须先导入它。 ```python -# using the `math` module to use -# additional mathematical functions +# 使用 `math` 模组里面的数学函数 >>> import math >>> math.sqrt(4.) 2.0 -# base-10 log +# 以10为底的对数 >>> math.log10(10.) 1.0 @@ -167,46 +166,46 @@ The standard library's math module provides us with many more mathematical funct -### Integers -As in traditional mathematics, an integer is any "whole" number: $\dots, -3, -2, -1, 0, 1, 2, 3, \dots$. +### 整数 +像传统数学一样,一个整数是任何没有小数点的数字:$\dots, -3, -2, -1, 0, 1, 2, 3, \dots$。 -Integers belong to the built-in type `int`, which can be used to convert objects to integers: +整数属于内置类 `int`,而 `int` 则可以用来将其它对象转化成整数: ```python >>> type(-3) int -# `1.3` is not an integer-type object +# `1.3` 不是整数对象 >>> isinstance(1.3, int) False -# converting a string to an integer +# 将字符串转化成整数 >>> int("10") 10 -# converting a floating-point number to an integer +# 将浮点数转化成整数 >>> int(1.3) 1 ``` -You can create as large an integer as you'd like; Python will allocate as much memory as needed (and ultimately, as is available) to store an integer's exact value: +整数想多大都可以;Python会分配相应该数字所需的内存来完全存储它(而不会丢失精度)。当然,说到底这还是受有多少内存可用的限制: ```python -# you can make an integer as large as you'd like +# 你可以创建一个很大的整数 >>> large_int = 281938481039848500192847576920 ``` -Integers have some built-in functions available to them, which are detailed in the [official documentation](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types). The utility of these will likely be quite obscure to new programmers. Just note that they are here for now. +整数有一些内置函数可用。完整的介绍可以在[官方说明文档](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types)中找到。很多这些函数的作用可能对新手而言比较难以理解。现在你只需要知道这些函数存在就行。 -### Floating-Point Numbers -A "floating-point" number is a number with a decimal point. Referred to as a "float" for short, this can be used to represent any number, up to a limited number of digits. +### 浮点数 +一个浮点数(floating-point number,或float)是有小数点的数字。这可以用来表达任何数字,但其精度受数字位数的限制。 -These objects belong to the built-in type `float`, which can be used to convert objects to floats: +这些对象属于内置类 `float`,而 `float` 则可以用来将其它对象转化成浮点数: ```python -# examples of "floating-point" numbers +# 几个浮点数的例子 >>> 100. ** 0.5 10.0 @@ -219,117 +218,114 @@ These objects belong to the built-in type `float`, which can be used to convert >>> type(-2.1) float -# the integer 10 is not a float-type object +# 整数 10 并不是浮点数 >>> isinstance(10, float) False -# including a decimal makes the number a float +# 但加上一个小数点会让其成为浮点数 >>> isinstance(10., float) True -# converting a string to a floating-point number +# 将字符串转化成浮点数 >>> float("10.456") 10.456 -# converting an integer to a floating-point number +# 将整数转化成浮点数 >>> float(-22) -22.0 ``` -Floats have a couple of built-in functions available to them, as detailed in the [official documentation](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float). +浮点数有几个内置的函数可用。具体内容在[官方说明文件](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float)中可以查阅。 -#### Scientific Notation -A float can also be created using familiar scientific notation. The character `e` is used to represent $\times 10$, and the proceeding number is the exponent. Here are some examples of traditional scientific notation, and their corresponding representation in Python: +#### 科学计数法 +浮点数也可以用常见的科学计数法来创建。字符 `e` 用来代表 $\times 10$,而在这字符后的数字是幂。以下为几个传统的科学计数法例子和它们对应的Python表达式: $1.38 \times 10^{-4} \rightarrow$ `1.38e-04` $-4.2 \times 10^{10} \rightarrow$ `-4.2e10` -Python will automatically display a float that possesses many digits in scientific notation: +Python将自动用科学计数法来显示位数多的浮点数: ```python -# python will display many-digit numbers using -# scientific notation ->>> 0.0000001 # seven leading-zeros +# Python会用科学计数法来显示多位浮点数 +>>> 0.0000001 # 7个前置0 1e-07 ``` -#### Understanding Numerical Precision -Whereas a Python integer can be made to be as large as you'd like, a floating-point number is *limited in the number of digits it can store*. That is, your computer will only use a set amount of memory, 8 bytes (32 bits) on most machines, to store the value of a floating-point number. +#### 理解数字精度 +虽然Python整数无大小限制,浮点数的精度*受限于它能存储多少位数*。具体来讲,你的电脑只会用固定量的内存(在大部分机器上是8字节,也就是32比特)来储存一个浮点数的值。 + +实际操作时,这意味着一个浮点数大概只能存储16位有效数字的*数值精度*。计算机并不能保证存这8字节之外的位数精度。比如说,接下来的代码定义了一个100位的整数。但当这个整数被转化成浮点数后,它只能保存16位的有效数字: -In effect, this means that a float can only be represented with a *numerical precision* of approximately 16 decimal places, when that number is written in scientific notation. The computer will not be able to reliably represent a number's digits beyond those accounted for by the allotted 8 bytes. For instance, the following Python integer is defined with 100 digits, but when this number is converted to a float, it only retains 15 decimal places in scientific notation: ```python -# Demonstrating the finite-precision of a float. +# 演示浮点数的有限精度 -# An integer with 100 digits - Python will use as -# much memory as needed to store an integer ->>> int("1"*100) # creates a string with 100 1s and makes it an int +# 一个100位的整数 +# Python会分配足够多的的内存来存储这个整数 +>>> int("1"*100) # 创建一个含有100个“1”的字符串并将其转化成整数 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 -# Converted to a float, it retains only -# 16 decimal places, when written in scientific -# notation. This is the precision permitted by -# 8 bytes of memory. ->>> float("1"*100) # creates a string with 100 1s and makes it a float +# 当将同样的字符串转化成浮点数时, +# 它只能存储16位的有效数字 +# 这也就是8字节内存能存储的大小 +>>> float("1"*100) # 创建一个含有100个“1”的字符串并将其转化成浮点数 1.111111111111111e+99 ``` -The computer cannot keep track of those last 84 decimal places because doing so would require more than 8 bytes of memory to store the entire value of that float. If you had been diligently counting stars in the sky (perhaps across many universes, this number far exceeds the estimated number of stars in our universe), you would have just lost track of over $1\times10^{83}$ of them simply by converting your integer count to a float! +计算机无法存储最后84位数字的原因是这样做会需要远超于8字节的内存去存储整个浮点数。假如你在数星星的话,用浮点数而不是整数来存储这个数字会让你漏掉其中整整 $1\times10^{83}$ 个! -As such, attempting to modify a floating point number in decimal places beyond its numerical precision does not have any effect: +因此,试图用超过浮点数精度的数值去修改该浮点数并不会有任何效果: ```python -# changing a float beyond its precision has no effect +# 用超过浮点数精度的数值去修改该浮点数并不会有任何效果 >>> 1. + 1e-16 1.0 ``` -Even in light of this discussion on float precision, you may be shocked and dismayed to see the following outcome of float arithmetic: +就算有了以上对浮点精度的讨论做铺垫,你也很可能会惊讶于以下浮点运算的结果: ```python -# the finite-precision of floats -# result in non-obvious behavior +# 这令人意外的结果源自浮点数的有限精度 >>> 0.1 + 0.1 + 0.1 - 0.3 == 0. False -# the effects of having finite numerical precision +# 浮点数的有限精度的效果 >>> 0.1 + 0.1 + 0.1 - 0.3 5.551115123125783e-17 ``` -This is not a quirk of Python; this is a [well-understood](https://docs.python.org/3/tutorial/floatingpoint.html) aspect of dealing with floating-point numbers with limited numerical precision. To accommodate this, don't check if two floats are "equal". Rather, you should check if they are "close enough in value". -Let me emphasize this: +这并不是什么Python的奇怪特征;这是一个已经被[完全理解](https://docs.python.org/3/tutorial/floatingpoint.html)的操作有限精度的浮点数的现象。为了应对这个问题,你不应该检查两个浮点数是否“相同”,而应该检查两个浮点数是否“够相近”。 +让我重点强调一下: - **You should never check to see if two floats are exactly equal in value. Instead, you should only check that two floats are approximately equal to one another**. +**你永远不应该检查两个浮点数是否完全相同。你应该检查两个浮点数是否足够相近。** -The `math` module has a very nice function for this; `math.isclose` will check if the relative difference between two numbers is less than $1 \times 10^{-9}$. You can change this tolerance value along with the type of tolerance-checking used by the function; see its documentation [here](https://docs.python.org/3/library/math.html#math.isclose). Because in the previous example we compare values that are close to 0, we will check if their absolute difference is sufficiently small: +`math` 模组有一个解决这个需求的函数;`math.isclose` 会检查两个数字之间的差是否小于 $1 \times 10^{-9}$。你可以修改这个函数使用的容忍值;详见此函数的[说明文档](https://docs.python.org/3/library/math.html#math.isclose)。因为在之前的例子中我们对比的数值都很接近0,我们将检查它们的差的绝对值是否够小: ```python -# checking if two float values are "almost equal" +# 检查两个浮点数是否“足够接近” >>> import math -# check: +# 检查 # | (0.1 + 0.1 + 0.1 - 0.3) - 0 | < 1x10^{-9} >>> math.isclose((0.1 + 0.1 + 0.1 - 0.3), 0., abs_tol=1e-9) True ``` -If you do not heed this lesson, it is inevitable that you will end up with serious, hard-to-find bugs in your code. Lastly, -when doing numerical work in Python (and any other programming language), you must understand that the finite numerical precision of floating-point numbers is a source of error, akin to error associated with imprecision with a measuring device, and should be accounted for in your analysis (if error analysis is warranted). +如果你不记住这一课,你未来绝对会导致一些严重,难查的bug。在Python(以及任何其它编程语言)中做和数字有关的工作时,你一定要理解浮点数的有限精度是一个错误源,就像测量工具的不精确一样。因此在错误分析的时候要考虑到它(如果你需要做错误分析的话)。 -Python's [decimal module](https://docs.python.org/3.0/library/decimal.html) can be used to define higher (or lower) precision numbers than permitted by the standard 8-byte floats. Furthermore, all arithmetic involving decimal numbers from this module is guaranteed to be *exact*, meaning that `0.1 + 0.1 + 0.1 - 0.3` would be exactly `0.`. There is also a built-in [fractions module](https://docs.python.org/3/library/fractions.html#module-fractions), which provides tools for working with exact representations of rational numbers. Although we will not be using them here, it is very important to keep in mind that these modules exist and that floating point numbers are not the only way around the number line in Python. +你可以用Python的[decimal模组](https://docs.python.org/3.0/library/decimal.html)来定义比标准8字节的浮点数更高(或更低)精度的数字。任何使用这个模组的数学计算都是*完全精确*的,也就是说 `0.1 + 0.1 + 0.1 - 0.3` 正好是 `0.`。Python还有一个自带的[fractions模组](https://docs.python.org/3/library/fractions.html#module-fractions)提供精确表达和操作有理数的工具。虽然我们不会在本资源中使用这些模组,但是你也应该知道这些模组的存在以及浮点数并不是唯一的选择这事实。 -### Complex Numbers -In mathematics, a "complex number" is a number with the form $a + bi$, where $a$ and $b$ are real-valued numbers, and $i$ is defined to be the number that satisfies the relationship $i^2 = -1$. Because no real-valued number satisfies this relationship, $i$ is called the "imaginary number". +### 复数 +在数学中,一个“复数”(complex number)是任何 $a + bi$ 形式的数字($a$ 和 $b$ 为实数,$i$ 的定义为满足 $i^2 = -1$ 关系的数)。因为没有任何实数满足上述关系,$i$ 被称为“虚数”。 -Weirdo electrical engineers use the symbol $j$ in place of $i$, which is why Python displays the complex number $2 + 3i$ as `2+3j` (this is actually because $i$ typically denotes current; we like electrical engineers too). +奇奇怪怪的电气工程师用符号 $j$ 来代替 $i$,所以Python会将复数 $2 + 3i$ 打印成 `2+3j`(实际原因是 $i$ 一般用来表达电流;我们还是要爱护电气工程师的)。 -Along with the `a + bj` syntax, built-in type `complex` can be used to create complex-type numbers: +除了 `a + bj` 格式之外,内置的 `complex` 类可以用来创建复数: ```python -# creating complex numbers +# 创建复数 >>> 2 + 3j (2+3j) @@ -346,22 +342,21 @@ complex True ``` -Note that `j` is not, by itself, reserved as a special placeholder for $i$. Rather, `j` must be preceded immediately with a numerical literal (i.e. you cannot use a variable) in order for the Python interpreter to treat it as a complex number. +请注意,`j` 自身并不是代表 $i$ 的特殊字符。只有在一个数字常量(numerical literal)(不是变量的数字)后的 `j` 才会被Python直译器理解为复数。 ```python -# `j` by itself is treated like any other character +# 仅仅 'j' 本身并没有什么特殊含义 >>> j -NameError: name 'j' is not defined +NameError: name 'j' is not defined(名字 'j' 未定义) -# `1j` is interpreted as the imaginary number +# 而 `1j` 会被理解为虚数 >>> (1j) ** 2 (-1+0j) ``` -You can access `a` and `b` from `a + bj`, the real and imaginary parts of the complex number, respectively. +你分别可以获取 `a + bj` 中的 `a` 和 `b`,也就是复数的实数(real)和虚数(imaginary)部分。 ```python -# Accessing the real and imaginary parts of -# a complex number. +# 获取复数的实数和虚数部分 >>> x = complex(1.2, -3.4) >>> x.real 1.2 @@ -369,15 +364,15 @@ You can access `a` and `b` from `a + bj`, the real and imaginary parts of the co -3.4 ``` -The `cmath` ("complex math") module provides a collection of mathematical functions defined for complex numbers. For a complete listing of these functions, refer to the [official documentation](https://docs.python.org/3/library/cmath.html#module-cmath). +`cmath`(“complex math”)模组定义了一组复数的数学函数。完整的列表可以在[官方说明文件](https://docs.python.org/3/library/cmath.html#module-cmath)找到。
-**Reading Comprehension: Working with numbers in Python** +**阅读理解:操作Python数字** -1\. In Python, performing an arithmetic operation, such as addition or multiplication, on two integers will return an integer, and performing an operation on two floats will return a float: +1\. 在Python中,对两个整数进行如加或乘的算术会返回一个整数,而对两个浮点数进行运算会返回一个浮点数: ```python >>> 2 * 3 6 @@ -386,37 +381,37 @@ The `cmath` ("complex math") module provides a collection of mathematical functi 6.0 ``` -For which operation, among `+ - * / **`, does this *not* hold? +上述语句对 `+ - * / **` 这些运算符中哪个*不*成立? -2\. What type of number will be returned if you perform a mathematical operation using an integer and a floating-point number? Does this hold for all the arithmetic operations? Determine this by trial and error. +2\. 对一个整数和一个浮点数进行数学运算会返回哪种数字?是否所有的运算符都遵循这一规律?请在命令行中进行尝试以得到答案。 -3\. Given the function $f(x) = e^{|x - 2|}$, make use of the `math` module to compute $f(-0.2)$. +3\. 定义 $f(x) = e^{|x - 2|}$。使用 `math` 模组来运算 $f(-0.2)$。 -4\. Using Python's syntax for scientific notation, write an expression that verifies that one trillion divided by one billion is equal to one thousand +4\. 使用Python的科学计数法语法来确认一万亿除以十亿等于一千。
-### Augmented Assignment Statements -Python provides a nice "shortcut" for updating a variable via an arithmetic operation. For example, suppose you want to increase the value of `x` by 1. Currently, we would update `x` as follows: +### 赋值语句的简写 +Python提供了一些方便你使用数学运算符更新变量的方式。假设你想要将 `x` 的值增加 1,你可能会如此操作: ```python -# incrementing `x` by 1 +# 将 `x` 增加 1 >>> x = 5 >>> x = x + 1 >>> x 6 ``` -We can make use of a special assignment operation `+=` to perform this update in an abbreviated way. +我们可以利用一个特殊的赋值符 `+=` 来简写这个更新操作。 ```python -# using `+=` to increment `x` by 1 +# 使用 `+=` 来将 `x` 增加 1 >>> x = 5 ->>> x += 1 # equivalent to: `x = x + 1` +>>> x += 1 # 这和 `x = x + 1` 等值 >>> x 6 ``` -`+=` is a type of *augmented assignment statement*. In general, an augmented assignment performs a mathematical operation on a variable, and then updates that variable using the result. Augmented assignment statements are available for all of the arithmetic operations. Assuming `x` and `n` are both types of numbers, the following summarizes the available arithmetic augmented assignment statements that we can perform on `x`, using `n`: +`+=` 是一种*增强赋值语句*(augmented assignment statement)。总的来讲,一个增强赋值语句会对一个函数进行某种数学运算,并用运算的结果更新该函数。每个算术运算符都有着相对应的增强的赋值语句。假设 `x` 和 `n` 为数字,以下列表将总结我们可以用 `n` 对 `x` 进行的增强算术赋值语句: - `x += n` $\rightarrow$ `x = x + n` - `x -= n` $\rightarrow$ `x = x - n` @@ -427,59 +422,59 @@ We can make use of a special assignment operation `+=` to perform this update in -### Improving The Readability of Numbers -Python version 3.6 introduced the ability to include underscores between the digits of a number as a visual delimiter. This character can be used to improve the readability of long numbers in your code. For example the number `662607004` can be rewritten as `662_607_004`, using `_` to delimit digits separated by orders of one thousand. Leading, trailing, or multiple underscores in a row are not allowed; otherwise this character can be included anywhere within a numerical literal. +### 提升数字的可读性 +Python 3.6版本提供了在数字位数之间插入下划线来视觉上划分它们的功能。这个符号可以用来提升多位数的可读性。比如说,利用 `_` 来区分每三位的数字,`662607004` 可以被重写成为 `662_607_004`。下划线不能出现在数字首位,尾位,或另一个下划线旁边,但除此以外这个符号可以出现在数字常量中间的任何位置。 ```python -# examples of using `_` as a visual delimiter in numbers ->>> 1_000_000 # this is nice! +# 利用 `_` 来视觉上划分数字 +>>> 1_000_000 # 这很实用! 1000000 -# this is gross but is permitted +# 虽然看起来挺恶心的,但这是合法的Python代码 >>> 2_3_4.5_6_7 234.567 -# underscores work with all variety of numerical literals +# 你可以在任何类型的数字中插入下划线 >>> 10_000j 10000j ```
-**Compatibility Warning** +**兼容性警告** -The permitted use of the underscore character, `_`, in numerical literals was introduced in Python 3.6. Thus utilizing this syntax in your code will render it incompatible with Python 3.5 and earlier. +在数字常量中插入下划线 `_` 的功能是在Python 3.6版本加入的。如果你使用此功能,那你的代码会和Python 3.5和更早的版本不兼容。
-## The Boolean Type -There are two boolean-type objects: `True` and `False`; they belong to the built-in type `bool`. We have already seen that the `isinstance` function either returns `True` or `False`, as a given object either is or isn't an instance of a specific type. +## 布尔类 +Python有两种布尔类(boolean)的对象:`True`(真)和 `False`(否);它们属于内置的 `bool` 类型。我们在之前见到 `isinstance` 函数根据对象是否是某类的实例(instance)而返回 `True` 或 `False`。 ```python -# the two boolean-objects: `True` and `False` +# 两种布尔类的对象:`True` 和 `False` >>> type(True) bool -# `False` is a boolean-type object +# `False` 是一个布尔类的对象 >>> isinstance(False, bool) True ``` -`True` and `False` must be specified with capital letters in Python. These should not be confused with strings; note that there are no quotation marks used here. +在Python中,`True` 和 `False` 必须要首字母大写。请不要将它们和字符串搞混;注意布尔值并两边没有引号。 -### Logic Operators -Python provides familiar operators for performing basic boolean logic: +### 逻辑运算符 +Python提供常见的布尔逻辑的操作符: -| Logic Operation | Symbolic Operator -| --------------- | ------------------- | -| `and` | `&` | -| `or` | | | +| 逻辑运算名称 | 运算符号 | +| ------------ | -------- | +| `and`(逻辑与) | `&` | +| `or` (逻辑或) | | | ```python -# demonstrating boolean-logic operators +# 演示布尔逻辑运算符 >>> True or False True @@ -490,24 +485,26 @@ False True ``` -Operator symbols are available in place of the reserved words `and` and `or`: +译者注:原文因为 `not`(逻辑否)在英文中很好理解没有多讨论。读者只需知道:`not` 返回输入的布尔值的反值。 + +你也可以使用 `and` 和 `or` 对应的运算符号: ```python -# demonstrating the symbolic logic operators ->>> False | True # equivalent to: `False or True` +# 演示逻辑运算符 +>>> False | True # 和 `False or True` 等值 True ->>> False & True # equivalent to: `False and True` +>>> False & True # 和 `False and True` 等值 False ``` -That being said, it is generally more "Pythonic" (i.e. in-vogue with Python users) to favor the use of the word-operators over the symbolic ones. +一般来讲,使用运算名称,而不是符号,是更加“Python风格“的做法(也就是说这个方法在Python编程者之间更时兴)。 -Multiple logic operators can be used in a single line and parentheses can be used to group expressions: +你可以在同行使用多个逻辑运算符,并用括号来细述运算顺序: ```python >>> (True or False) and True True ``` -Comparison statements used in basic mathematics naturally return boolean objects. +基本的比大小语句自然会返回布尔类的对象。 ```python >>> 2 < 3 True @@ -519,12 +516,12 @@ False False ``` -The `bool` type has additional utilities, which will be discussed in the "Conditional Statements" section. +`bool` 类有着其它方便操作的方法。我们将在“条件语”小节讨论它们。 -### Boolean Objects are Integers -The two boolean objects `True` and `False` formally belong to the `int` type in addition to `bool`, and are associated with the values `1` and `0`, respectively: +### 布尔值对象其实就是整数 +`True` 和 `False` 这两个布尔值对象正式而言也是 `int` 类型的成员,其分别对应 `1` 和 `0`: ```python >>> isinstance(True, int) @@ -540,47 +537,48 @@ True 0 ``` -As such, they can be used in mathematical expressions interchangeably with `1` and `0` +因此,在数学运算中它们和 `1` 和 `0` 的作用一样: ```python ->>> 3*True - False # equivalent to: 3*1 + 0 +>>> 3*True - False # 和 3*1 + 0 等值 3 ->>> True / False # equivalent to: 1 / 0 +>>> True / False # 和 1 / 0 等值 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () ----> 1 True / False ZeroDivisionError: division by zero +(因为除以零所以直译器报错) ``` -The purpose of having `True` and `False` double as integers is beyond the scope of this section. It is simply useful to be aware of these facts so that this behavior is not completely alien to you as you begin to write code in Python. +为何 `True` 和 `False` 同时也是整数的原因超出了本节的纲领。熟悉这一特征会让你在写Python代码的时候避免一些错误。
-**Reading Comprehension: Boolean expressions** +**阅读理解:布尔表达式** -1\. Assuming `x` is a an integer-type, write a comparison statement that will return `True` if `x` is an even number, and `False` otherwise. (Hint: recall the purpose of the `%` operator) +1\. 假设 `x` 是整数类。编写一个表达式,在 `x` 是偶数时返回 `True`,其它情况返回 `False`。(提示:回忆 `%` 运算符的功能) -2\. Assuming `x` and `y` are both real-valued numbers (i.e. not complex numbers), write a line of code that will return `False` if: `x` and `y` are within 0.9 of one another, and `x` is a positive number. (Hint: try writing the expression that will return `True` for this condition, and then negate it) +2\. 假设 `x` 和 `y` 都是实数(也就是不是复数的数字)。编写一行代码,在以下情况中返回 `False`:`x` 和 `y` 相差小于0.9,且 `x` 大于零。(提示:尝试先编写在这个情况中会返回 `True` 的代码,然后再取反) -3\. Write an expression that returns `True` if `x` is a boolean-type object or a float-type object. +3\. 编写一个表达式,当 `x` 是布尔类型或浮点类型对象时返回 `True`。
-## The None-Type -There is a simple type, `NoneType` that has exactly one object: `None`. `None` is used to represent "null"... nothing. +## None类型 +`NoneType`(None类型)仅仅只有一个对象:`None`。`None` 用来表达“无”/“空”,也就是什么都没有的意思。 ```python -# `None` is the *only* object belonging to NoneType +# `None` 是*唯一*属于NoneType的对象 >>> type(None) NoneType ``` -As such, instead of checking if an object belongs to NoneType, you should simply check if the object is `None`. Python reserves `is` as an operation that checks if two objects are identical. This is different than `==`, which checks if two objects are associated with the same value or state: +因此,与其检查某对象是否属于NoneType,你应该直接检查该对象是否就是 `None`。Python保留 `is` 为检查两个对象是否相同的运算符。这和检查两个对象是否有着同样的值或态的 `==` 运算符不一样: ```python -# Check if an object "is" None, instead -# of checking if it is of NoneType +# 检查对象是否*是*(is)None,而不是 +# 检查对象是否是NoneType类的实例 >>> x = 22 >>> x is None @@ -594,14 +592,15 @@ True >>> y is None True ``` -`None` appears frequently, and is often used as a placeholder in code. Here is a simple example where `None` could be useful; don't worry that this code may not make perfect sense to you yet: +译者注:`x is not None` 和 `not (x is None)` 等值,但前者因更符合英文语法而也被支持。 + +`None` 经常作为占位符使用。以下代码将演示 `None` 在实际操作中的用法;如果你并不能完全理解这代码,不要担心: ```python -# Demonstrating the use of `None` as a placeholder +# 演示将 `None` 作为占位符的用法 -# In this code, we want to get the first -# item in a list that is greater than 10, and notify -# the user if there is no such number +# 在本代码中,我们想要找到列表中第一个大于10的物件 +# 如果该物件不存在,我们将如实告诉用户 large_num = None @@ -617,42 +616,41 @@ if large_num is None: -## Strings -### Introducing the string type -The string type is used to store written characters. A string can be formed using: +## 字符串 +### 字符串类型简介 +字符串(string)类型被用于存储多个字符。你可以用一下语法创建字符串: -- single quotes: `'Hello world'` -- double quotes: `"Hello world"` -- triple quotes: `"""Hello world"""` or `'''Hello world'''` +- 单引号:`'Hello world'` +- 双引号:`"Hello world"` +- 三引号:`"""Hello world"""` 或 `'''Hello world'''` ```python -# Strings contain written characters, even those -# not found in the english alphabet! +# 字符串可以存储任何字符, +# 不仅仅是英文字母表中的字母! >>> "hello, 你好, Olá, 123" 'hello, 你好, Olá, 123' ``` -By default, Python 3 uses [UTF-8 unicode](https://docs.python.org/3/howto/unicode.html#unicode-howto) to represent this wide variety of characters. Don't worry about this detail beyond making note of it, for now. +Python 3默认使用[UTF-8 unicode](https://docs.python.org/3/howto/unicode.html#unicode-howto)来表达这些多样化的字符。暂时没必要太过关注这个细节,知道它存在就行。 -Strings belong to the built-in `str` type, which can be used to convert non-string objects into strings. +字符串属于内置的 `str` 类型。`str` 则可以用来将非字符串对象转化成字符串。 ```python -# the type `str` +# `str` 类型 >>> type("hello") str >>> isinstance("83", str) True -# Using the type `str` to convert non-string objects -# into strings. +# 利用 `str` 类型来将非字符串对象转化成字符串 >>> str(10.34) '10.34' >>> str(True) 'True' ``` -Once a string is formed, it cannot be changed (without creating an entirely new string). Thus a given string object cannot be "mutated" - a string is an *immutable* object. +当一个字符串被创建后,它的值无法被改变(除非你创建一个全新的字符串)。因此,任何一个字符串都无法被“改变”——字符串是*不可变*(immutable)的对象。 -As the string stores a *sequence* of characters, Python provides a means for accessing individual characters and subsequences of characters from a string: +因为Python存储一*序列*(sequence)的字符,Python提供了调用字符串中单个字符和子字符串的工具: ```python >>> sentence = "The cat in the hat." >>> sentence[0] @@ -660,24 +658,24 @@ As the string stores a *sequence* of characters, Python provides a means for acc >>> sentence[0:3] 'The' ``` -Strings are not the only sequence-type in Python; lists and tuples are examples of sequences as well. We will reserve a separate section to learn about the common interface that Python has for all of its types that are sequential in nature, including the "indexing" and "slicing" demonstrated here. +字符串并不是Python中唯一的序列类;列表(list)和元组(tuple)也同样是序列的一种。我们在未来将专门花一节课来讨论Python提供的通用序列操作。这包括了以上展示的“索引“(indexing)和”切片“(slicing)。 -### String essentials -We will only scratch the surface with strings, touching on some essentials. Please refer to the [official Python tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) for a more extensive, but still informal, overview of strings. +### 字符串基础 +我们只会学习一些字符串的基础。如果你想要一个更全面的非正式字符串教程,请查阅[官方Python教程](https://docs.python.org/3/tutorial/introduction.html#strings)。 -In a string, `\n` is treated as a single character. It denotes a new-line in a string, and will be rendered thusly when the string is printed. Similarly, `\t` will render as a tab-character. +在字符串中,`\n` 被视为一个字符。它代表着字符串的新行(new-line)。在打印时它也会如此显示。相似的 `\t` 会显示为一个tab字符。 ```python -# using `\n` to create a newline +# 使用 `\n` 来创建新行 >>> print("hi...\n...bye") hi... ...bye ``` -Using triple quotes allows you to write a block-string, meaning that you can include text on multiple lines, and it is all still treated as one string: +三引号将允许你编写一整块字符串,也就是说你可以在多行中编写同一个字符串: ```python -# using triple-quotes to write a multi-line string +# 使用三引号来编写一个多行字符串 >>> x = """ I am a string. I am part of the same string. me... too!""" @@ -687,80 +685,146 @@ I am part of the same string. ``` -Python's strings have a large number of fantastic, built-in functions available to them. It is *very important* that you familiarize yourself with these functions by looking over [the official documentation](https://docs.python.org/3/library/stdtypes.html#string-methods). To demonstrate a few of these: +Python的字符串有着大量很有用的内置函数。熟悉了解这些函数*极其重要*。详见[官方说明文件](https://docs.python.org/3/library/stdtypes.html#string-methods)。以下是其中一些函数的演示: ```python -# demonstrating a few of the built-in functions for strings ->>> "hello".capitalize() +# 演示几个字符串的内置函数 +>>> "hello".capitalize() # 译者注:首字母大写 'Hello' -# join a list of strings, using "..." +# 使用“...”来讲多个字符串连接在一起 >>> "...".join(["item1", "item2", "item3"]) 'item1...item2...item3' -# split a string wherever ", " occurs +# 每当“, ”出现时切分字符串 >>> 'item1, item2, item3'.split(", ") ['item1', 'item2', 'item3'] -# does this string end with ".py"? +# 该字符串是否以“.py”结尾? >>> "script.py".endswith(".py") True -# does this string start with "sc"? +# 该字符串是否以“sc”打头? >>> "script.py".startswith("sc") True -# insert objects into a string, in its -# "formatting" fields {} +# 在占位符 {} 中将对象转化为字符串并插入 >>> "x: {}, y: {}, z: {}".format(3.2, 8.4, -1.0) 'x: 3.2, y: 8.4, z: -1.0' -# Are the characters in the string -# numerical digits? +# 该字符串的字符是否时数字位数? >>> "7".isdigit() True ``` -### Official documentation for strings -It is highly recommended that you take time to read over all of the functions that are built-in to a string. +### 格式化字符串 +Python提供多种设置字符串格式的语法;利用这些语法,我们可以轻松地将变量数值插入到字符串中,利用空格对齐行列,并控制字符串显示小数点后几位数。本节旨在向读者展示这些不同的字符串格式。 + +如果你想要完整(但仍然易懂)的Python字符串格式教程,请查阅[pyformat.info](https://pyformat.info)。你也可以查阅[官方教程](https://docs.python.org/3/library/string.html#format-examples)。 + +在Python 3中,你可以使用 `format` 方法来格式化字符串: + +```python +# 使用 `format` 来用函数值代替占位符 +>>> "{name} is {age} years old".format(name="Bruce", age=80) +'Bruce is 80 years old' + +# 以下语法会前置空格来保证字符串至少有8字符长 +>>> "{item:>8}".format(item="stew") +' stew' +``` +你有时可能会见到别人用 `%` 运算符来格式化字符串: + +```python +# 使用 `%` 来格式化字符串(注意不要使用此方法) +>>> name = "Selina" +>>> "My name is %s" % name +'My name is Selina' +``` +这是Python 2的遗留物;你应注意避免使用此语法。 + +如果你在用Python 3.6和之后的版本,你可以使用f-string(f字符串),一种很方便格式化字符串的方法。以下是一个f字符串的范例: + +```python +# “f字符串”范例 +>>> batman = 12 +>>> catwoman = 10 +>>> f"Batman has {batman} apples. Catwoman has {catwoman} apples. Together, they have {batman + catwoman} apples" +'Batman has 12 apples. Catwoman has 10 apples. Together, they have 22 apples' +``` + +请注意f字符串是一种特殊语法;在第一个引号前输入小写字符f来使用f字符串: +```python +# 这是一个常见的空字符串 +>>> "" +'' + +# 这是一个空的f字符串 +>>> f"" +'' +``` + +f字符串的特殊之处在于它允许我们在字符串*中*编写Python代码;任何在 `{}` 中的表达式都会作为Python代码被执行,其结果将会被转化成字符串并插入在 `{}` 在f字符串中的位置。 -- [Built-in functions for strings](https://docs.python.org/3/library/stdtypes.html#string-methods) -- [Formatting strings](https://docs.python.org/3.4/library/string.html#format-examples) +```python +>>> x = 7.9 +>>> f"x is a {type(x)}-number. Its value is {x}. The statement 'x is greater than 5' is {x > 5}" +"x is a -number. Its value is 7.9. The statement 'x is greater than 5' is True" +(“x是一个浮点数类数字。它的值为7.9。表达式‘x大于5’为真”) +``` + +如例中所见,这将允许我们优雅地在字符串创建时插入变量并甚至调用函数的输出。 + +
+ +**f字符串兼容性**: + +f字符串是Python 3.6才加入的新语法。它在之前的Python版本不可用。 +
+ +### 字符串的官方说明文档 +本文强烈建议读者花些时间了解所有字符串的自带函数。 + +- [字符串自带函数](https://docs.python.org/3/library/stdtypes.html#string-methods) +- [格式化字符串](https://docs.python.org/3/library/string.html#format-examples)
-**Reading Comprehension: Strings** +**阅读理解:字符串** -To answer some of the following questions, you will need to peruse the documentation for the built-in functions of strings. It may take a bit of experimentation to understand the documentation's use of square-brackets to indicate optional inputs for a function. +为了回答以下问题,你会需要查阅字符串内置函数的说明文档。你可能需要进行一些尝试才能理解说明文档的“[]”格式(用于表达函数的可选输入)。 -1\. Use a function that will take the string `"cat"`, and returns the string `" cat "` (which has a length of 11, including the letters c, a, t). Now, change the way you call the function so that it returns `"----cat----"` instead. +1\. 使用一个函数,在输入字符串 `"cat"` 时返回字符串 `" cat "`(输出的长度为11个字符;这包含字符c,a,t)。之后,修改你调用该函数的方法以返回 `"----cat----"`。 -2\. Replace the first three periods of this string with a space-character: `"I.am.aware.that.spaces.are.a.thing"` +2\. 用空格代替以下字符串的前三个句号:`"I.am.aware.that.spaces.are.a.thing"` -3\. Remove the whitespace from both ends of: `" basket "` +3\. 去除该字符串两边的所有空格:`" basket "`。 - -4\. Create a string that will print as (the second line begins with a tab-character): + +4\. 创建一个打印时会如下显示的字符串(第二行打头的是一个tab符号): ``` Hello over there ``` -5\. Convert the integer `12` to the string `"12"`. +5\. 将整数 `12` 转化成字符串 `"12"`。 + +6\. 只有13岁和以上的孩子可以观看电影《反斗智多星》。设变量 `name`(字符串)和 `age`(整数)。使用f字符串来显示:"NAME is old enough to watch the movie: BOOL"(“NAME可以看这电影:BOOL”)。NAME应该用孩子的名字来代替,而BOOL在孩子13岁或以上时为 `True`,不然为 `False`。
- -## Lists -A `list` is a type of Python object that allows us to store a sequence of other objects. One of its major utilities is that it provides us with means for updating the contents of a list later on. +## 列表 +一个 `list`(列表)是一个允许我们存储一序列Python对象的对象。列表的一大功能就是我们在未来可以更新列表中的内容。 -A list object is created using square-brackets, and its contents are separated by commas: `[item1, item2, ..., itemN]`. Its contents need not be of the same type of object. +你可以用方括号来创建列表,并用逗号区分其中的成员:`[item1, item2, ..., itemN]`。它的成员可以是各种不同的类型。 + +译者注:注意使用英文的方括号和逗号。 ```python -# a list-type object stores a sequence of other objects +# 列表对象可以存储一序列的其它对象 >>> [3.5, None, 3.5, True, "hello"] [3.5, None, 3.5, True, 'hello'] @@ -768,142 +832,141 @@ A list object is created using square-brackets, and its contents are separated b list >>> isinstance([1, 2], list) -True +True -# constructing an empty list +# 空列表 >>> [] [] -# constructing a list with only one member +# 只有一个成员的列表 >>> ["hello"] ["hello"] ``` -You can also include variables, equations, and other Python expressions in the list constructor; Python will simplify these expressions and construct the list with the resulting objects. +你也可以在创建列表时使用变量,公式,和其它Python表达式;Python会计算这些表达式并用计算的结果作为列表的成员。 ```python -# the list constructor will simplify expressions -# and store their resulting objects +# 创建列表时会计算表达式并储存计算后的输出对象 >>> x = "hello" >>> [2 < 3, x.capitalize(), 5**2, [1, 2]] [True, 'Hello', 25, [1, 2]] ``` -The built-in `list` type can be used to convert other types of sequences (and more generally, any *iterable* object, which we will discuss later) into a list: +内置的 `list` 类型可以用来将其它任何类型的序列(更广义来讲,任何*可迭代*的对象——我们会在之后对其进行讨论)转化成列表: ```python -# `list` forms a list out of the contents of other sequences +# `list` 利用其它序列的内容来创建新列表 >>> list("apple") ['a', 'p', 'p', 'l', 'e'] ``` -### Lists are sequences -Like a string, the ordering of a list's contents matters, meaning that a list is sequential in nature. +### 列表是序列 +就像字符串一样,列表内容的排列顺序是很重要的。这也就是说,列表是序列性(sequential)的。 ```python -# A list's ordering matters +# 列表是分顺序的 >>> [1, "a", True] == [1, True, "a"] False ``` -Thus a list supports the same mechanism for accessing its contents, via indexing and slicing, as does a string. Indexing and slicing will be covered in detail in the next section. +因此,像字符串一样,你可以通过索引(indexing)和切片(slicing)来访问列表的内容。我们将在下一节中更具体地介绍索引和切片。 ```python -# Accessing the contents of a list with indexing and slicing +# 通过索引和切片来访问列表的内容 >>> x = [2, 4, 6, 8, 10] -# `x` contains five items +# `x` 里有5个物件 >>> len(x) 5 -# access the 0th item in the list via "indexing" +# 通过索引来访问列表的第0个物件 >>> x[0] 2 -# access a subsequence of the list via "slicing" +# 通过切片来访问列表的子序列 >>> x[1:3] [4, 6] ``` -### Lists can be "mutated" -We will encounter other types of containers in Python, what makes the list stand out is that the *contents of a list can be changed after the list has already been constructed*. Thus a list is an example of a *mutable* object. +### 列表是可变的 +我们会在之后遇到其它的Python容器。使得列表不同的是*列表的内容可以在列表创建后被修改*。因此,列表是*可变*对象的一种。 ```python -# changing a list after it has been constructed +# 在列表被创建后修改它 >>> x = [2, 4, 6, 8, 10] >>> y = [2, 4, 6, 8, 10] -# "set" the string 'apple' into position 1 of `x` +# 将列表 `x` 第1位的物件“设置”(set)成字符串 'apple' >>> x[1] = "apple" >>> x [2, 'apple', 6, 8, 10] -# replace a subsequence of `y` +# 修改 `y` 的子序列 >>> y[1:4] = [-3, -4, -5] >>> y [2, -3, -4, -5, 10] ``` -The built-in list-functions "append" and "extend" allow us to add one item and multiple items to the end of a list, respectively: +自带的列表函数“append”和“extend”允许我们分别在列表结尾添加一个和多个的成员: ```python >>> x = [2, 4, 6, 8, 10] -# use `append` to add a single object to the end of a list +# 用 `append` 在列表结尾添加一个对象 >>> x.append("moo") >>> x [2, 4, 6, 8, 10, 'moo'] -# use `extend` to add a sequence of items to the end of a list +# 用 `extend` 在列表结尾添加一序列的对象 >>> x.extend([True, False, None]) >>> x [2, 4, 6, 8, 10, 'moo', True, False, None] ``` -The "pop" and "remove" functions allow us to remove an item from a list based on its position in the list, or by specifying the item itself, respectively. +“pop”和“remove”函数允许我们分别根据成员在列表中的位置和值来将它们从列表中移出。 ```python >>> x = ["a", "b", "c", "d"] -# pop the position-1 item out from a list -# `pop` will return the item that gets removed. +# 将列表中位置1的物件“pop”(跳)出来 +# `pop` 会返回被移出的物件 >>> x.pop(1) 'b' >>> x ['a', 'c', 'd'] -# remove the object "d" from the list +# 将对象 `"d"` 从列表中移出 >>> x.remove("d") >>> x ['a', 'c'] ``` -### Official documentation for lists -It is highly recommended that you take time to read over all of the functions that are built-in to a list. These are all designed to allow us to either inspect or mutate the contents of a list. +### 列表的官方说明文档 +本文强烈建议读者花些时间了解列表的所有自带函数。这些函数都旨在帮助我们访问或修改列表的内容。 -- [Built-in functions for a list](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) +- [列表的内置函数](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
-**Reading Comprehension: Lists** +**阅读理解:列表** -To answer some of the following questions, you will need to peruse the documentation for the built-in functions of lists. +为了回答以下问题,你会需要查阅列表内置函数的说明文档。 -1\. Create a list whose sole entry is the `None` object. +1\. 创建一个列表,其唯一的物件是 `None` 对象。 -2\. Assign to the variable `k` a list that contains an integer, a boolean, and a string, in that order. Then, add two more entries to the end of the list: a float and a complex number. +2\. 向变量 `k` 赋值一个内容为一个整数,一个布尔值,和一个字符串(顺序也是如此)的列表。然后在列表结尾添加两个项目:一个浮点数和一个复数。 -3\. Alphabetize the list of names: `["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"]`. +3\. 根据字母顺序排序以下列表:`["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"]`。
-## Summary -The term "object" is a catch-all in Python, meaning anything that we can assign to a variable. Objects behave differently from one another according to what "type" a given object is. +## 总结 +“对象”(object)在Python中泛指任何可以赋值于一个变量的东西。对象根据其“类型”(type)不同会有不同的行为。 -We reviewed several fundamental object types in Python: +我们复习了Python几种不同的基本对象类型: -- `int`, `float`, `complex`: the numerical types -- `bool`: the boolean type. `True` and `False` are the only boolean-type objects -- `NoneType`: the "null" type; `None` is *the only object that belongs to this type* -- `str`: the string type -- `list`: the list type +- `int`,`float`,`complex`:数字类型 +- `bool`:布尔(boolean)类型,其唯二的布尔类对象为 `True` 和 `False` +- `NoneType`:“空”类;`None` 是*唯一的这类对象* +- `str`:字符串类 +- `list`:列表类 -The built-in function `type` permits us to check the type of any object: +Python自带的 `type` 函数允许我们查看任何对象的类型: ```python >>> type(3.2) float @@ -912,20 +975,20 @@ float bool ``` -The built-in function `isinstance` should be used to check if an object is of a specific type: +我们应该用自带的 `isinstance` 函数来查看一个对象是否属于某类型: ```python >>> x = 2 + 3 >>> isinstance(x, int) True ``` -The only exception to this is if you want to check if an object is of the type `NoneType`, since this is only possible if the object is `None`; thus it is "cleaner" to directly check this: +唯一例外的是当你想要检查某个对象是否属于 `NoneType` 类型,因为这类型只有 `None` 一个对象;因此,如下直接检查会更加“干净”: ```python >>> x = None >>> x is None True ``` -Objects of different types have different built-in functions available to them: +不同类型的对象有着不同的内置函数可用: ```python >>> x = "I am a farmer.. moo" >>> x.upper() @@ -941,17 +1004,17 @@ Objects of different types have different built-in functions available to them: [1, 2, 3] ``` -You should leverage the official documentation, for which links were provided throughout this section, whenever you are wondering how to best do a specific task with a given type of object. +当你在试图寻找操作某类型对象的最佳方法时,你应当查阅官方说明文档(本节多次提供其链接)。 -As a final reminder, we saw that that an integer in Python is able to hold a value with arbitrarily-many digits. A floating-point number, on the other hand, is restricted in the number of "significant" digits it can hold. Thus, where it is perfectly fine to check if two integers are exactly equal: +最后,Python整数类可以存储任意多的位数,而浮点数只能存储有限的“有效”位数。因此,你可以直接检查两个整数是否完全相等: ```python -# checking if two integers are equal is great! +# 检查两个整数是否完全相等没有任何问题! >>> 2 + 2 == 4 True ``` -you should never rely on two floats being exactly equal. Instead, check if they are close in value: +但你不应该检测两个浮点数是否完全相等。你应该检查它们的值是否足够接近: ```python -# checking if two floats are equal is lame! +# 检查两个浮点数是否完全相等会有一些奇怪的结果! >>> 0.1 + 0.1 + 0.1 - 0.3 == 0. False @@ -959,37 +1022,37 @@ False True ``` -It is very important to remember this issue of the limited numerical precision of a floating point number. +切记浮点数的有限精度问题。 -## Links to Official Documentation +## 官方说明文档链接 -- [Integers](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types) -- [Floating point numbers](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float) -- [The standard library's math module](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions) -- [The standard library's complex-valued math module](https://docs.python.org/3/library/cmath.html#module-cmath) -- [Strings](https://docs.python.org/3/library/stdtypes.html#string-methods) - - [String tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) - - [Formatting strings](https://docs.python.org/3.4/library/string.html#format-examples) -- [Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) +- [整数](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types) +- [浮点数](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-float) +- [标准库的math模组](https://docs.python.org/3/library/math.html#number-theoretic-and-representation-functions) +- [标准库的复数math模组](https://docs.python.org/3/library/cmath.html#module-cmath) +- [字符串](https://docs.python.org/3/library/stdtypes.html#string-methods) + - [字符串教程](https://docs.python.org/3/tutorial/introduction.html#strings) + - [字符串格式](https://docs.python.org/3.4/library/string.html#format-examples) +- [列表](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**Understanding the modulo operator: Solution** +**理解模运算符:解** -If `n` is an integer, then 2 will divide into it evenly, and thus there is no remainder. If `n` is odd, then `n / 2` must have a remainder of 1. Thus: +如果 `n` 是偶数,那么它将被2整除,所以余数为0。如果 `n` 是单数,那 `n / 2` 的余数为1。所以: -- `n % 2 ` = 0 if `n` is an even number -- `n % 2 ` = 1 if `n` is an odd number +- 当 `n` 是偶数时 `n % 2 ` = 0 +- 当 `n` 是单数时 `n % 2 ` = 1 -**Working with numbers in Python: Solution** +**操作Python数字:解** -1\. The division operator, `/`, will return a floating-point number even if it is operating on two integer-type numbers. +1\. 除法操作符 `/` 永远都会返回浮点数,就算它在将两个整数相除。 -2\. For all of the arithmetic operations, `+ - * / **`, operating on a floating-point number and an integer will return a floating-point number: +2\. 所有算术运算符 `+ - * / **` 对一个整数一个浮点数操作时都会返回一个浮点数: ```python >>> 2 * 3.0 6.0 @@ -998,7 +1061,7 @@ If `n` is an integer, then 2 will divide into it evenly, and thus there is no re 1.0 ``` -3\. Given the function $f(x) = e^{|x - 2|}$, make use of the `math` module to compute $f(-0.2)$. +3\. 设函数 $f(x) = e^{|x - 2|}$。用 `math` 模组来计算 $f(-0.2)$。 ```python >>> from math import exp >>> x = -0.2 @@ -1006,9 +1069,9 @@ If `n` is an integer, then 2 will divide into it evenly, and thus there is no re 9.025013499434122 ``` -4\. Using Python's syntax for scientific notation, write an expression that verifies that one trillion divided by one billion is equal to one thousand. +4\. 使用Python的科学计数法语法来确认一万亿处以十亿等于一千。 -> As cautioned above, we should avoid checking to see if two floating point numbers are exactly equal, and instead simply ensure that they are close in value. Keep in mind that a number written Python's using scientific syntax will produce a float. +> 如上文所警示的一样,我们应该避免检查两个浮点数是否完全相等,而应当检查两浮点数是否足够相近。注意在Python中用科学计数法写出的数字会是浮点类的。 ```python >>> from math import isclose @@ -1018,34 +1081,34 @@ True -**Boolean expressions: Solutions** +**布尔表达式:解** ```python -# 1. Write an a comparison-statement that will return -# True if x is an even number +# 1. 编写一个表达式,在 `x` 是偶数时返回 `True`, +# 其它情况返回 `False`。 x%2 == 0 ``` ```python -# 2. Write a line of code that will return False if: -# x and y are within 0.9 of one another, and x is a positive number. +# 2. 编写一行代码,在以下情况中返回 `False`: +# `x` 和 `y` 相差小于0.9,且 `x` 大于零。 not (abs(x - y) < 0.9 and 0 < x) -# alternatively, +# 或者 abs(x - y) > 0.9 or 0 > x ``` ```python -# 3. Write an expression that returns True if -# x is a boolean-type object or a float-type object +# 3. 编写一个表达式,当 `x` 是布尔类型 +# 或浮点类型对象时返回 `True`。 isinstance(x, bool) or isinstance(x, float) ``` -**Strings: Solutions** +**字符串:解** ```python -# 1. Use a function that will take the string "cat" -# and returns the string " cat " +# 1. 使用一个函数,在输入字符串 `"cat"` 时 +# 返回字符串 `" cat "` >>> "cat".center(11) ' cat ' @@ -1054,15 +1117,13 @@ isinstance(x, bool) or isinstance(x, float) ``` ```python -# 2. Replace the first three periods of this string with -# a space-character: +# 2. 用空格代替以下字符串的前三个句号: >>> "I.am.aware.that.spaces.are.a.thing".replace(".", " ", 3) 'I am aware that.spaces.are.a.thing' ``` ```python -# 3. Remove the whitespace from both ends -# of: " basket " +# 3. 去除该字符串两边的所有空格:`" basket "` >>> " basket ".strip() 'basket' ``` @@ -1075,26 +1136,41 @@ Hello ``` ```python -# 5. Convert the integer 12 to the string "12" +# 5. 将整数 `12` 转化成字符串 `"12"`。 >>> str(12) '12' ``` + +只有13岁和以上的孩子可以观看电影《反斗智多星》。假设你有函数 `name`(字符串)和 `age`(整数)。使用f字符串来显示:"NAME is old enough to watch the movie: BOOL"(“NAME可以看这电影:BOOL”)。NAME应该用孩子的名字来代替,而BOOL在孩子至少13岁以上时应为 `True`,不然为 `False`。为测试我们使用 `name = "Alfred"`,`age = 10`. + +```python +# 6. 只有13岁和以上的孩子可以观看电影《反斗智多星》。 +# 假设你有函数 `name`(字符串)和 `age`(整数)。 +# 使用f字符串来显示:"NAME is old enough to watch +# the movie: BOOL"(“NAME可以看这电影:BOOL”)。 +# 用NAME应该用孩子的名字来代替,而BOOL在孩子至少13岁以上 +# 时应为 `True`,不然是 `False`。 +>>> name = "Alfred" +>>> age = 10 +>>> f"{name} is old enough to watch the movie: {age >= 13}" +'Alfred is old enough to watch the movie: False' +``` + -**Lists: Solutions** +**列表:解** ```python -# Create a list whose sole entry is the None object. +# 创建一个列表,其唯一的物件是 `None` 对象。 >>> [None] [None] ``` ```python -# 2. Assign the variable k to a list that contains an -# integer, a boolean, and a string, in that order. -# Then, add two more entries to the end of the -# list - a float and a complex number. +# 2. 向变量 `k` 赋值一个内容为一个整数,一个布尔值, +# 和一个字符串(顺序也是如此)的列表。然后在列表结尾 +# 添加两个项目:一个浮点数和一个复数。 >>> k = [4, False, "moo"] >>> k.extend([3.14, complex(9, -2)]) >>> k @@ -1102,13 +1178,13 @@ Hello ``` ```python -# 3. Alphabetize the list of names: +# 3. 根据字母顺序排序以下列表: >>> names = ["Jane", "Adam", "Ryan", "Bob", "Zordon", "Jack", "Jackenzie"] -# The documentation for `sort` says that the sorting happens "in-place". This -# means that the original list is replaced by the sorted list. The alternative -# would be that `sort` returns a new, sorted list, without changing the list -# assigned to `names`. +# `sort` 的说明文档说排序是“in-place”(当场)的, +# 这意思就是原本的列表会被新的排序好的列表代替。 +# 如果不是“in-place”的话,那可能 `sort` 会返回一个排序好 +# 的列表,而不修改原本名为 `names` 的列表。 >>> names.sort() >>> names ['Adam', 'Bob', 'Jack', 'Jackenzie', 'Jane', 'Ryan', 'Zordon'] diff --git a/Python/Module2_EssentialsOfPython/ConditionalStatements.md b/Python/Module2_EssentialsOfPython/ConditionalStatements.md index 95af737..c2d86e4 100644 --- a/Python/Module2_EssentialsOfPython/ConditionalStatements.md +++ b/Python/Module2_EssentialsOfPython/ConditionalStatements.md @@ -4,108 +4,108 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Conditional Statements, Difficulty: Easy, Category: Section :keywords: if, else, elif, inline if, switch statement, comparison operator, bool, truth, is operator -``` + -# Conditional Statements +# 条件语
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-In this section, we will be introduced to the `if`, `else`, and `elif` statements. These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false. For example, the following code will square `x` if it is a negative number, and will cube `x` if it is a positive number: +在本节中,我们将会介绍 `if`,`else`,和 `elif` 语句。它们允许你编写仅仅在某些条件满足时才会执行的代码片段,或者在条件不满足时执行某些其它代码。比如说,以下代码在 `x` 是负数的时候返回 `x` 的平方,在 `x` 是正数时返回 `x` 的立方: ```python -# a simple if-else block +# 简单的if-else区块 if x < 0: x = x ** 2 else: x = x ** 3 ``` -Please refer to the "Basic Python Object Types" subsection to recall the basics of the "boolean" type, which represents True and False values. We will extend that discussion by introducing comparison operations and membership-checking, and then expanding on the utility of the built-in `bool` type. +请通过“基本对象类型“一节来回忆布尔类型(代表真或否值)的一些基础特征。我们将会延续该节的讨论来介绍比较运算和成员检查,并讨论内置 `bool` 类的更多有用之处。 -## Comparison Operations -Comparison statements will evaluate explicitly to either of the boolean-objects: `True` or `False`. There are eight comparison operations in Python: +## 比较运算 +比较语句(comparison statement)最后一定会返回某个布尔对象:`True` 或 `False`。在Python中总共有八种比较运算: -| Operation | Meaning | +| 运算符 | 含义 | | --------- | ----------------------- | -| `<` | strictly less than | -| `<=` | less than or equal | -| `>` | strictly greater than | -| `>=` | greater than or equal | -| `==` | equal | -| `!=` | not equal | -| `is` | object identity | -| `is not` | negated object identity | +| `<` | 小于(不等于) | +| `<=` | 小于或等于 | +| `>` | 大于(不等于) | +| `>=` | 大于或等于 | +| `==` | 等于 | +| `!=` | 不等于 | +| `is` | 相同对象 | +| `is not` | 不相同对象 | -The first six of these operators are familiar from mathematics: +其中前六个运算符和数学中常见的相对应: ```python >>> 2 < 3 True ``` -Note that `=` and `==` have very different meanings. The former is the assignment operator, and the latter is the equality operator: +注意 `=` 和 `==` 有着两个很不一样的含义。前者是赋值运算符,而后者是等值运算符: ```python ->>> x = 3 # assign the value 3 to the variable `x` ->>> x == 3 # check if `x` and 3 have the same value +>>> x = 3 # 对变量 `x` 赋值 3 +>>> x == 3 # 检查 `x` 和 3 是否有着同样的值 True ``` -Python allows you to chain comparison operators to create "compound" comparisons: +Python允许你连接多个对比运算符来创建“复式”(compound)对比: ```python ->>> 2 < 3 < 1 # performs (2 < 3) and (3 < 1) +>>> 2 < 3 < 1 # 等值于 (2 < 3) and (3 < 1) False ``` -Whereas `==` checks to see if two objects have the same value, the `is` operator checks to see if two objects are actually the *same* object. For example, creating two lists with the same contents produces two *distinct* lists, that have the same "value": +`==` 运算符检查两个对象是否有着同样的值,而 `is` 运算符检查两个对象是否是*相同的*对象。比如说,创建两个有着一样内容的列表会得到两个*不同*的列表,但它们的“值”一样: ```python -# demonstrating `==` vs `is` +# 演示 `==` 对比 `is` >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> x == y True -# `x` and `y` reference equivalent, but distinct lists +# `x` 和 `y` 引用两个等值但不同的列表 >>> x is y False ``` -Thus the `is` operator is most commonly used to check if a variable references the `None` object, or either of the boolean objects: +因此 `is` 运算符最常用来检查一个变量是否引用 `None` 对象,或两个布尔对象中的一个: ```python >>> x = None >>> x is None True -# (2 < 0) returns the object `False` -# thus this becomes: `False is False` +# (2 < 0) 返回对象 `False` +# 因此这会成为:`False is False` >>> (2 < 0) is False True ``` -Use `is not` to check if two objects are distinct: +使用 `is not` 来检查两个对象是否不是同一个对象: ```python >>> 1 is not None True @@ -113,8 +113,8 @@ True -## `bool` and Truth Values of Non-Boolean Objects -Recall that the two boolean objects `True` and `False` formally belong to the `int` type in addition to `bool`, and are associated with the values `1` and `0`, respectively: +## `bool` 和非布尔类对象的真值 +请回忆两个布尔对象 `True` 和 `False` 严格来讲即属于 `bool` 也属于 `int` 类型,并分别有着值 `1` 和 `0` 这些知识点: ```python >>> isinstance(True, int) @@ -141,43 +141,43 @@ ZeroDivisionError Traceback (most recent call last) ZeroDivisionError: division by zero ``` -Likewise Python ascribes boolean values to non-boolean objects. For example,the number 0 is associated with `False` and non-zero numbers are associated with `True`. The boolean values of built-in objects can be evaluated with the built-in Python command `bool`: +类似的,Python也会对非布尔对象提供相应的布尔值。比如说,数字0对应着 `False`,而任何非0的数字则对应 `True`。内置对象的布尔值可以通过Python内置的命令 `bool` 来得出: ```python -# Using `bool` to access the True/False -# value of non-boolean objects +# 使用 `bool` 来查看非布尔类对象 +# 的布尔值为 `True` 或 `False` >>> bool(0) False ``` -and non-zero Python integers are associated with `True`: +任何非0的Python整数对应 `True`: ```python -# nonzero values evaluate to `True` +# 非0值最后计算为 `True` >>> bool(2) True ``` -The following built-in Python objects evaluate to `False` via `bool`: +以下的内置Python对象通过 `bool` 对应 `False`: - `False` - `None` -- Zero of any numeric type: `0`, `0.0`, `0j` -- Any empty sequence, such as an empty string or list: `''`, `tuple()`, `[]`, `numpy.array([])` -- Empty dictionaries and sets +- 任何数字类的0:`0`, `0.0`, `0j` +- 任何空序列,如空字符串或列表:`''`,`tuple()`,`[]`,`numpy.array([])` +- 空词典(dictionary)或集(set) -Thus non-zero numbers and non-empty sequences/collections evaluate to `True` via `bool`. +因此任何非0的数字或非空的序列或集合都会通过 `bool` 对应 `True`。
-**Takeaway**: +**经验**: -The `bool` function allows you to evaluate the boolean values ascribed to various non-boolean objects. For instance, `bool([])` returns `False` wherease `bool([1, 2])` returns `True`. +`bool` 函数允许你得到非布尔类对象对应的布尔值。比如说,`bool([])` 返回 `False`,而 `bool([1, 2])` 返回 `True`。
-## `if`, `else`, and `elif` -We now introduce the simple, but powerful `if`, `else`, and `elif` conditional statements. This will allow us to create simple branches in our code. For instance, suppose you are writing code for a video game, and you want to update a character's status based on her/his number of health-points (an integer). The following code is representative of this: +## `if`,`else`,和 `elif` +我们现在将介绍简单而强大的 `if`,`else`,和 `elif` 条件语句(conditional statement)。这将允许我们在代码中创建简单的分枝。比如说,假设你在为某电子游戏编写代码,并想要根据你角色的血量(整数)来更新ta的状态,下面的代码就是一个例子: ```python if num_health > 80: @@ -190,102 +190,99 @@ else: status = "dead" ``` -Each `if`, `elif`, and `else` statement must end in a colon character, and the body of each of these statements is [delimited by whitespace](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope). +每个 `if`,`elif`,和 `else` 语句必须由冒号结尾,且其中所有语句都必须由[空格限定](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python使用空格来限定区域)。 -The following pseudo-code demonstrates the general template for conditional statements: +以下的伪代码演示条件语句的通用模版: ``` if : - the code within this indented block is executed if.. - - bool() is True + 本缩进区域的代码只有在以下条件满足时才会被执行... + - bool() 为 True elif : - the code within this indented block is executed if.. - - bool() was False - - bool() is True + 本缩进区域的代码只有在以下条件满足时才会被执行... + - bool() 之前为 False + - bool() 为 True ... ... elif : - the code within this indented block is executed if.. - - bool() was False - - bool() was False + 本缩进区域的代码只有在以下条件满足时才会被执行... + - bool() 之前为 False + - bool() 之前为 False ... ... - - bool() was False - - bool() is True + - bool() 之前为 False + - bool() 为 True else: - the code within this indented block is executed only if - all preceding expressions were False + 本缩进区域的代码只有在 + 之前所有表达式为 False 时 + 才会被执行... ``` -In practice this can look like: +实际运用时它可以看起来是这样: ```python x = [1, 2] if 3 < len(x): - # bool(3 < 2) returns False, this code - # block is skipped + # bool(3 < 2) 返回 False,所以此区块的代码将被跳过 print("`x` has more than three items in it") elif len(x) == 2 - # bool(len(x) == 2) returns True - # this code block is executed + # bool(len(x) == 2) 返回 True,此区块的代码被执行 print("`x` has two items in it") elif len(x) == 1 - # this statement is never reached + # 此语句根本没有被检查 print("`x` has one items in it") else: - # this statement is never reached + # 此语句根本没有被检查 print("`x` is an empty list") "`x` has two items in it" ``` -In its simplest form, a conditional statement requires only an `if` clause. `else` and `elif` clauses can only follow an `if` clause. +在最简洁的格式下,一个条件语句只需要一个 `if` 句段。`else` 和 `elif` 句段只能在一个 `if` 句段之后。 ```python -# A conditional statement consisting of -# an "if"-clause, only. - +# 一个只有“if”句段的条件语句 x = -1 if x < 0: x = x ** 2 -# x is now 1 +# `x` 现在为 1 ``` -Similarly, conditional statements can have an `if` and an `else` without an `elif`: +类似的,条件语句可以有一个 `if` 和一个 `else` 而没有任何 `elif`: ```python -# A conditional statement consisting of -# an "if"-clause and an "else" +# 一个有一个“if”句段和一个“else”句段 +# 的条件语句 x = 4 if x > 2: x = -2 else: x = x + 1 -# x is now -2 +# `x` 现在为 -2 ``` -Conditional statements can also have an `if` and an `elif` without an `else`: +条件语句也可以有一个 `if` 和一个 `elif` 而没有 `else`: ```python -# A conditional statement consisting of -# an "if"-clause and an "elif" +# 一个有一个“if”句段和一个“elif”句段 +# 的条件语句 x = 'abc' if len(x) < 9: x = x * 3 elif len(x) > 40: x = 'cba' -# x is now 'abcabcabc' +# `x` 现在为 'abcabcabc' ``` -Note that only one code block within a single if-elif-else statement can be executed: either the "if-block" is executed, or an "elif-block" is executed, or the "else-block" is executed. Consecutive if-statements, however, are completely independent of one another, and thus their code blocks can be executed in sequence, if their respective conditional statements resolve to `True`. +请注意在一个if-elif-else语句中只有其中一段可以被执行;要么“if”区块的代码被执行,要么一个“elif”区块的代码被执行,要么“else”区块的代码被执行。但是,背靠背的if语句是完全独立于对方的。因此它们的代码区块可能在单次运行中都被执行(假设它们对应的条件语句都最后为 `True`)。 ```python -# consecutive if-statements are independent +# 连续的if语句是互相独立的 x = 5 y = 0 @@ -295,16 +292,16 @@ if x < 10: if x < 20: y += 1 -# y is now 2 +# y 现在为 2 ```
-**Reading Comprehension: Conditional statements** +**阅读理解:条件语句** -1\. Assume `my_list` is a list. Given the following code: +1\. 设 `my_list` 为一个列表。根据以下代码: ```python first_item = None @@ -312,13 +309,13 @@ if my_list: first_item = my_list[0] ``` -What will happen if `my_list` is `[]`? Will `IndexError` be raised? What will `first_item` be? +如果 `my_list` 为 `[]`,会发生什么?这是否会产生一个 `IndexError`?`first_item` 会是什么? -2\. Assume variable `my_file` is a string storing a filename, where a period denotes the end of the filename and the beginning of the file-type. Write code that extracts only the filename. +2\. 设变量 `my_file` 为一个存储着文件名的字符串,其中英文句号 `.` 代表着文件名的结尾和文件类型的开始。编写代码来获取 `my_file` 的文件名。 -`my_file` will have at most one period in it. Accommodate cases where `my_file` does *not* include a file-type. +`my_file` 中最多只会有一个句号。妥善处理 `my_file` *没有*文件类型的情况。 -That is: +也就是说: - `"code.py"` $\rightarrow$ `"code"` - `"doc2.pdf"` $\rightarrow$ `"doc2"` @@ -328,8 +325,8 @@ That is: -### Inline if-else statements -Python supports a syntax for writing a restricted version of if-else statements in a single line. The following code: +### 单行的if-else语句 +Python支持一个单行版本的if-else语句,其功能比较有限。以下代码: ```python if num >= 0: @@ -338,31 +335,31 @@ else: sign = "negative" ``` -can be written in a single line as: +可以被简写成: ```python sign = "positive" if num >=0 else "negative" ``` -This is suggestive of the general underlying syntax for inline if-else statements: +这代表了单行(inline)if-else语句的内在语法:
-**The inline if-else statement**: +**单行if-else语句**: -The expression `A if else B` returns `A` if `bool()` evaluates to `True`, otherwise this expression will return `B`. +表达式 `A if else B` 当 `bool()` 为 `True` 时返回 `A`,不然该表达式会返回 `B`。
-This syntax is highly restricted compared to the full "if-elif-else" expressions - no "elif" statement is permitted by this inline syntax, nor are muli-line code blocks within the if/else clauses. +和完整的“if-elif-else”表达式对比,这个语法是极其受限制的——它不允许“elif”语句,也不允许if/else之间有多行的代码块。 -Inline if-else statements can be used anywhere, not just on the right side of an assignment statement, and can be quite convenient: +单行if-else语句可以在任何地方使用,不仅仅是在赋值语句的右侧。这有时很方便: ```python -# using inline if-else statements in different scenarios +# 在不同情况下使用单行if-else语句 >>> x = 2 -# will store 1 if `x` is non-negative -# will store 0 if `x` is negative +# 如 `x` 并不是负数,这将储存 1 +# 如 `x` 为负数,这将储存 0 >>> my_list = [1 if x >= 0 else 0] >>> my_list [1] @@ -370,31 +367,31 @@ Inline if-else statements can be used anywhere, not just on the right side of an >>> "a" if x == 1 else "b" 'b' ``` -We will see this syntax shine when we learn about comprehension statements. That being said, this syntax should be used judiciously. For example, inline if-else statements ought not be used in arithmetic expressions, for therein lies madness: +我们将在讨论列表理解语句(list comprehension statement)时注意到这个语法很有用的地方,但请注意谨慎使用这一语法。比如说,不要在数学表达式中使用单行if-else语句,因为最后的代码令人抓狂: ```python -# don't ever do this...ever! +# 永远不要这么做,永远! 2 - 3 if x < 1 else 1 + 6*2 if x >= 0 else 9 ``` -## Short-Circuiting Logical Expressions -Armed with our newfound understanding of conditional statements, we briefly return to our discussion of Python's logic expressions to discuss "short-circuiting". In Python, a logical expression is evaluated from left to right and will return its boolean value as soon as it is unambiguously determined, *leaving any remaining portions of the expression unevaluated*. That is, the expression may be *short-circuited*. +## 短路逻辑表达式 +在对条件语句有了更深刻的理解之后,我们将扩展我们对Python逻辑表达式的研究来讨论短路(short-circuiting)。在Python中,一个逻辑表达式会从左到右运算,并在表达式结果确定的那一步就返回,且*不会运算表达式剩下的部分*。也就是说,表达式可以*短路*。 -For example, consider the fact that an `and` operation will only return `True` if both of its arguments evaluate to `True`. Thus the expression `False and ` is guaranteed to return `False`; furthermore, when executed, this expression will return `False` *without having evaluated* `bool()`. +比如说,`and` 运算仅仅会在它两边的表达式都为 `True` 时才会返回 `True`。因此,表达式 `False and ` 一定会返回 `False`;同时,这个表达式会返回 `False` 而*不运算* `bool()`。 -To demonstrate this behavior, consider the following example: +为了演示这一行为,请见下面的例子: ```python -# demonstrating short-circuited logic expressions ->>> False and 1/0 # evaluating `1/0` would raise an error +# 演示短路逻辑表达式 +>>> False and 1/0 # 运算 `1/0` 会导致错误 False ``` -According to our discussion, the pattern `False and` short-circuits this expression without it ever evaluating `bool(1/0)`. Reversing the ordering of the arguments makes this clear. +根据上文的讨论,`False and` 会短路这个表达式,让它不运算 `bool(1/0)` 就返回。换转参数顺序会明显地揭示这一点。 ```python -# expressions are evaluated from left to right +# 表达式是从左到右运算的 >>> 1/0 and False --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) @@ -404,66 +401,66 @@ ZeroDivisionError Traceback (most recent call last) ZeroDivisionError: division by zero ``` -In practice, short-circuiting can be leveraged in order to condense one's code. Suppose a section of our code is processing a variable `x`, which may be either a [number](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Number-Types) or a [string](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Strings). Suppose further that we want to process `x` in a special way if it is an all-uppercased string. The code +在实际操作中,你可以通过短路来浓缩你的代码。假设我们代码的一节在处理变量 `x`,其可能是一个[数字](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#数字类型)或[字符串](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#字符串)。假设我们当 `x` 是全大写的字符串时想要有特殊的处理方式。以下代码 ```python -# this will raise an error if `x` is not a string +# 这在 `x` 不是字符串时会报错 if x.isupper(): - # do something with the uppercased string + # 对此大写字符串进行操作 ``` -is problematic because `isupper` can only be called once we are sure that `x` is a string; this code will raise an error if `x` is a number. We could instead write +是有问题的,因为 `isupper` 只应该在我们确定 `x` 是字符串之后才调用;如果 `x` 是一个数字,我们的代码会报错。我们可以重写代码 ```python -# a valid but messy way to filter out non-string objects +# 一个可用但难看的过滤非字符串对象的方法 if isinstance(x, str): if x.isupper(): - # do something with the uppercased string + # 对此大写字符串进行操作 ``` -but the more elegant and concise way of handling the nestled checking is to leverage our ability to short-circuit logic expressions. +但一个更加优雅和简短的处理多层次检测的方法是短路逻辑表达式。 ```python -# utilizing short-circuiting to concisely perform all necessary checks +# 利用短路来简写必要的检查 if isinstance(x, str) and x.isupper(): - # do something with the uppercased string + # 对此大写字符串进行操作 ``` -See, that if `x` is not a string, that `isinstance(x, str)` will return `False`; thus `isinstance(x, str) and x.isupper()` will short-circuit and return `False` without ever evaluating `bool(x.isupper())`. This is the preferable way to handle this sort of checking. This code is more concise and readable than the equivalent nested if-statements. +请注意如果 `x` 不是字符串,那 `isinstance(x, str)` 会返回 `False`;因此 `isinstance(x, str) and x.isupper()` 会短路并直接返回 `False`,且不运算 `bool(x.isupper())`。这是这种检查任务的推荐结局方法。这代码对比等值的多层if语句更简短和可读。
-**Reading Comprehension: short-circuited expressions** +**阅读理解:短路表达式** -Consider the preceding example of short-circuiting, where we want to catch the case where `x` is an uppercased string. What is the "bug" in the following code? Why does this fail to utilize short-circuiting correctly? +回忆前文检查 `x` 是大写字符串的范例。以下代码的“bug“是什么?为什么它并没有正确地利用短路? ```python -# what is wrong with me? +# 我做错了什么? if x.isupper() and isinstance(x, str): - # do something with the uppercased string + # 对此大写字符串进行操作 ```
-## Links to Official Documentation +## 官方说明文档连接 -- [bool](https://docs.python.org/3/library/functions.html#bool) -- [Truth testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) -- [Boolean operations](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not) -- [Comparisons](https://docs.python.org/3/library/stdtypes.html#comparisons) -- ['if' statements](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement) +- [布尔值](https://docs.python.org/3/library/functions.html#bool) +- [检查真值](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) +- [布尔操作符](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not) +- [对比](https://docs.python.org/3/library/stdtypes.html#comparisons) +- ['if'语句](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**Conditional statements** +**条件语句:解** -1\. If `my_list` is `[]`, then `bool(my_list)` will return `False`, and the code block will be skipped. Thus `first_item` will be `None`. +1\. 如果 `my_list` 为 `[]`,那 `bool(my_list)` 会返回 `False`,而对应的代码块则会被跳过。因此 `first_item` 会是 `None`。 -2\. First, check to see if `.` is even contained in `my_file`. If it is, find its index-position, and slice the string up to that index. Otherwise, `my_file` is already the file name. +2\. 首先,检查 `my_file` 是否包含 `.`。如果是,找到它的索引并对字符串进行切片(切到该索引)。如果不是,`my_file` 就已经是文件名了。 ```python my_file = "code.pdf" @@ -477,14 +474,14 @@ else: -**Short-circuited expressions** +**短路表达式:解** -The code +此代码 ```python -# what is wrong with me? +# 我做错了什么? if x.isupper() and isinstance(x, str): - # do something with the uppercased string + # 对此大写字符串进行操作 ``` -fails to account for the fact that expressions are always evaluated from left to right. That is, `bool(x.isupper())` will always be evaluated first in this instance and will raise an error if `x` is not a string. Thus the following `isinstance(x, str)` statement is useless. +并没有考虑表达式从左到右运算的顺序。也就是说,在这个例子中 `bool(x.isupper())` 永远都会首先被运算,并且会在 `x` 不是字符串时报错。因此,之后的 `isinstance(x, str)` 语句完全没用。 diff --git a/Python/Module2_EssentialsOfPython/DataStructures.md b/Python/Module2_EssentialsOfPython/DataStructures.md index f7889e7..a313128 100644 --- a/Python/Module2_EssentialsOfPython/DataStructures.md +++ b/Python/Module2_EssentialsOfPython/DataStructures.md @@ -4,146 +4,145 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Data Structures, Difficulty: Medium, Category: Section :keywords: Big-O, complexity, efficiency, algorithm, interview preparation, list, tuple, sequence -``` + -# Data Structures (Part I): Introduction -Here we survey Python's built-in data structures. You should already be familiar with its lists and tuples, two data structures that facilitate working with sequential data. Two other critical, built-in data structures to be introduced are: +# 数据结构(第一部分):简介 +我们在此介绍Python内置的数据结构(data structure)。你应该已经了解了列表和元组,两个帮助处理序列数据的数据结构。我们将会介绍另外两个重要的内置数据结构: -- dictionary: a mapping from "keys" to "values" -- sets: an unordered collection of items that can be used to perform set-algebraic operations (e.g. union and intersection) +- 词典(dictionary):一对一对应“键”(key)和“值”(value) +- 集(set):用来进行集运算(如并集和交集)的无序集合 -These data structures are not merely convenient constructs with some nice pre-written functionality; they also provide an interface to some optimized core utilities that have been written in C (or whatever language your Python interpreter is written in). For example, let's write a function that checks if an item is contained within an iterable: +这些数据结构不仅仅是一些有着好用核心功能的方便构造题;它们同时也提供了用C语言(或你使用的Python直译器编译用的语言)编译的高效核心功能的接口。比如说,让我们来编写一个检查某对象是否为可迭代物成员的函数: ```python def is_in(seq, target): - """ Returns True if `target` is contained in `seq`.""" + """ 如果 `target` 在 `seq` 中则返回真""" for item in seq: if item == target: return True return False ``` -This function mirrors the C-algorithm that Python uses "under the hood" for checking for membership in a list (assuming you are using the CPython interpreter, which you almost definitely are). Because their function is implemented "at a lower level", and need not be interpreted, we expect it to be faster than ours: +以上函数和Python在“幕后”使用的C语言成员检测算法(当然,这是假设你在使用CPython直译器,但极大可能是这个情况)是一样的。因为内置的成员检测函数是在“更底层”实现的并因此不需要被直译,所以它比我们在Python中定义的函数更快: ```python >>> x = [1, "moo", 3, True, 5, None, 7, 8] ->>> is_in(x, -1) # takes 980 nanoseconds on my machine +>>> is_in(x, -1) # 在我的机子上花了 980 纳秒 False ->>> -1 in x # takes 320 nanoseconds on my machine +>>> -1 in x # 在我的机子上花了 320 纳秒 False ``` -Here, Python's built-in sequence-membership function is 3x faster than using our own function. Furthermore, it will be important to know the advantages provided by each of the data structures. For instance, testing for membership in a set is even faster than is checking for membership in a list: +在此,Python的内置成员检测函数比我们的版本快了三倍。同时,我们应该了解各个数据结构的优势。比如说,集(set)的成员检测比列表还要快: ```python -# test for membership in a list ->>> -1 in [1, "moo", 3, True, 5, None, 7, 8] # takes 295 nanoseconds on my machine +# 在列表中检测是否为成员 +>>> -1 in [1, "moo", 3, True, 5, None, 7, 8] # 在我的机子上花了 295 纳秒 False -# test for membership in a set ->>> -1 in {1, "moo", 3, True, 5, None, 7, 8} # takes 65 nanoseconds on my machine +# 在集中检测是否为成员 +>>> -1 in {1, "moo", 3, True, 5, None, 7, 8} # 在我的机子上花了 65 纳秒 False ``` -We get a 4.5x speedup in our membership test just by using a set instead of a list, because the use of a set permits Python to use an entirely different algorithm for checking for membership. On our end, we merely replaced square brackets with curly braces! Hopefully this is sufficient motivation for learning about Python's data structures and the algorithms that they utilize "under the hood". +通过使用集而不是列表,我们得到了4.5倍的速度优化。这是因为集允许Python使用一个完全不同的成员检测算法。在Python程序员的角度上,我们仅仅将方括号替换成了花括号!我希望以上范例为你提供了足够学习Python数据结构和它们“幕后”使用的算法的理由。
-**Takeaway**: +**经验**: -Python's data structures come with a wealth of built-in functionality. Furthermore, understanding where each data structure "shines" is critical for writing efficient Python code. It is not necessary to memorize this information, but you should know that it exists and should be referenced frequently. +Python的数据结构有着自己内置的功能。同时,理解每个数据结构适合的工作对编写高效的Python代码极其重要。你不需要死记这些信息,但是你应该知道这些信息存在并经常查阅这些信息。
-## Describing Algorithm Complexity -In order to meaningfully compare the relative efficiency of algorithms, it is useful to summarize how algorithms "scale" with problem size. Two sorting algorithms may be comparable when sorting tens of items, and yet they may have wildly different performances when sorting thousands of items. +## 描述算法复杂度 +为了有意义地比较算法的效率,总结算法在问题大小变化时如何表现是很有用的信息。两个排序算法可能在排列几十个项目时速度相当,但它们完全可能在排列几千个项目时有着很不一样的效率。 -"Big-O" notation allows us to denote how an algorithm's run time scales against problem size. Specifically, it signifies the "worst-case scenario" performance of an algorithm. +“大O”符号(big-O notation)允许我们表达算法在问题大小变化时运算时间如何改变。具体来讲,它代表着算法在“最坏情况下”的表现。 -Let's take, for instance, the `is_in` function that we wrote at the beginning of this section. In it, we iterate over a collection to check if it contains a specific item. The worst-case scenario for this algorithm is when the item is not a member of the collection at all - we have to iterate over the entire collection before we can conclude that it does not possess our item. So if we increase the collection to be $n$ times larger in size, it should take $n$ times as long to iterate over it to determine that the item is not a member of the collection (again, dealing with the worst-case scenario). Because the worst-case scenario run time of `is_in` scales linearly with the size of the collection, $n$, we denote it's run time complexity, using big-O notation, as $\mathcal{O}(n)$. +比如说,拿在本节开始写的 `is_in` 函数来讲,我们迭代了一个集合并检查它是否有着某个项目。这个算法的最坏情况就是当项目并不是集合的成员——我们需要迭代整个集合才能确定它并不拥有我们要找的项目。所以如果我们将该集合的大小扩大 $n$ 倍,那它会花 $n$ 倍多的时间来迭代整个集合并决定一个项目不是其成员(在此同样假设最坏情况)。因为 `is_in` 的最坏情况的运行时间和集合的大小 $n$ 呈线性关系,所以我们用大O符号来将该算法的运行时间复杂度写为 $\mathcal{O}(n)$。 -Now suppose we did a truly terrible job writing a membership algorithm, and performed a nested iteration over our collection: +现在,假设我们写的成员检查函数很糟糕,其进行了嵌套迭代: ```python def is_in_slow(seq, target): - """ Returns True if `target` is contained in `seq`.""" + """ 如果 `target` 为 `seq` 成员,返回真。""" for item in seq: - # for each item in seq, iterate over seq in its entirety! + # 我们为seq中的项目重新迭代整个seq! for item2 in seq: if item == target: return True return False ``` -For each item in `seq` we iterate over `seq` again, thus in the worst-case scenario we need to iterate over $n$ items, $n$ separate times - a total of $n^{2}$ "steps" in our algorithm. Thus we would say that `is_in_slow` is a $\mathcal{O}(n^{2})$ algorithm: whereas doubling size of `seq` would increase the run time of our $\mathcal{O}(n)$ algorithm by a factor of 2 (linear scaling), it would increase the run time of this $\mathcal{O}(n^{2})$ algorithm by 4 (quadratic scaling). +我们为 `seq` 中的每个项目重新迭代 `seq` 一次,因此在最坏情况下我们需要迭代 $n$ 个成员 $n$ 次——总共在算法中走了 $n^{2}$ “步”。因此,我们说 `is_in_slow` 是一个 $\mathcal{O}(n^{2})$ 的算法:当我们将 `seq` 的大小翻倍时,我们的 $\mathcal{O}(n)$ 算法会花两倍多的时间(线性增加),而我们的 $\mathcal{O}(n^{2})$ 算法会花四倍多的时间(平方增加)。 -Here is a more formal description of this notation: +以下是大O符号更加正式的定义:
-**"Big-O" Notation**: Suppose that $n$ denotes the "size" of the input to an algorithm, and that the mathematical expression $f(n)$ describes how many computational steps the algorithm must take in its *worst-case scenario*, given that input. Then the algorithm's run time complexity can be denoted using the **"Big-O"** notation: $\mathcal{O}(f(n))$. +**“大O”符号**(big-O notation):假设 $n$ 代表着算法输入的“大小”,且数学表达式 $f(n)$ 描述该算法在*最坏情况*下需要花多少计算步骤处理大小为 $n$ 的输入,那么算法的运行时间复杂度用**“大O”符号**表达为 $\mathcal{O}(f(n))$。
-A few important notes: +几个重要的点: -- We only care about the "highest-order" term in $f(n)$. That is, $\mathcal{O}(n + n^{2})$ should just be written as $\mathcal{O}(n^{2})$. -- We never care about constant factors in our scaling. That is, even if an algorithm iterates over a sequence twice, its big-O complexity should be written as $\mathcal{O}(n)$, rather than $\mathcal{O}(2n)$. -- An algorithm whose run time *does not depend on the size of its input* is a $\mathcal{O}(1)$ algorithm. - - Example: a function that returns the second element from a list. -- There are more nuanced methods for analyzing algorithm complexity than solely considering the worst-case scenario, which can be overly pessimistic. Know that "big-O" notation can be used to convey mean performance, [amortized](https://en.wikipedia.org/wiki/Amortized_analysis) performance, and other types of analysis. Here, we will simply stick to the worst-case analysis. +- 我们仅仅在乎 $f(n)$ 最高次数的项。也就是说,$\mathcal{O}(n + n^{2})$ 应被写为 $\mathcal{O}(n^{2})$。 +- 我们永远不在乎关系中的常数。也就是说,就算一个算法迭代某序列两次,它的大O复杂度应该被写为 $\mathcal{O}(n)$,而不是 $\mathcal{O}(2n)$。 +- 一个运行时间*不根据输入大小而改变*的算法是一个 $\mathcal{O}(1)$ 算法。 + - 例:一个返回列表中第二个成员的函数。 +- 我们有其它更加微妙,不仅仅考虑最坏情况的分析算法复杂度的方法,因为最坏情况分析可能太过悲观。“大O”符号“也可以用来代表平均表现,[摊销](https://en.wikipedia.org/wiki/Amortized_analysis)(amortized)表现,和其它分析类型。在此,我们仅仅使用最坏情况分析。
-**Takeaway**: +**经验**: -We will be using the "big-O" notation, $\mathcal{O}(f(n))$, to summarize the performance of the algorithms used by Python's data structures. +我们将会使用“大O”符号 $\mathcal{O}(f(n))$ 来总结Python数据结构使用的算法的表现。
-## Sequential Data Structures: Lists and Tuples -The "Sequence Types" section already introduced lists and tuples. Recall that both provide the same interface for accessing and summarizing the contents of a heterogeneous sequence of objects. However, a list can be mutated - updated, removed from, and added to - whereas a tuple cannot be mutated. Thus a list is *mutable*, whereas a tuple is *immutable*. Here you will find a summary of the algorithmic complexities of many of the built-in functions that work on sequential data structures. +## 序列性数据结构:列表和元组 +“序列类型”小节已经介绍了列表和元组。请回忆这两个数据结构都提供了相同的交互界面来访问和总结其不同类型对象的成员序列。但是,列表是可以被改变的——你可以对其更新,删除,并添加项目——而元组不可变。因此列表*可变*,而元组*不可变*。在本节你将会找到很多操作序列数据结构的内置函数的算法复杂度。 -For a complete rundown of the functions available to Python's list, go [here](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists). +你可以在[这里](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)找到所有的Python列表函数。 -#### List/Tuple Complexities -Let `seq` represent a **list or tuple** of length $n$; $i$ and $j$ are integers drawn randomly from the interval $[0, n-1]$; $k$ is the length of any subsequence involved in the operation. The following is a summary of the complexities associated with various common operations using lists and tuple (according to their implementations in CPython): +#### 列表/元组复杂度 +设 `seq` 为长度为 $n$ 的**列表或元组**;$i$ 和 $j$ 为从区间 $[0, n-1]$ 中随意抽取的整数;$k$ 为任何在此操作中使用的子序列的长度。以下为各种常见的列表和元组操作(根据CPython的实现)的复杂度: -|Operation| Complexity | Explanation | +|操作| 复杂度 | 解释 | |---|---|---| -|`len(seq)`|O(1)| Return the number of items in the sequence | -|`seq[i]`| O(1) | Retrieve any item from the sequence | -|`seq[i:j]`| O(k) | Retrieve a length-k slice from the sequence | -|`for item in seq..`| O(n) | Iterate over the sequence | -|`obj in seq`| O(n) | Check if `obj` is a member of `seq` | -|`seq.count(obj)`| O(n) | Count the number of occurrences of `obj` in `seq` | -|`seq.index(obj)`| O(n)| Return position-index of `obj` in `seq` | +|`len(seq)`| O(1)| 返回序列中成员的数量 | +|`seq[i]`| O(1) | 从序列中获取单个成员 | +|`seq[i:j]`| O(k) | 从序列中获取长度k的切片 | +|`for item in seq..`| O(n) | 迭代序列 | +|`obj in seq`| O(n) | 检查 `obj` 是否为 `seq` 的成员 | +|`seq.count(obj)`| O(n) | 返回 `obj` 在 `seq` 出现的次数 | +|`seq.index(obj)`| O(n)| 返回 `obj` 在 `seq` 中的索引 | -#### List Complexities -Here we consider some mutating operations, like `append`, that are available to lists and not tuples. It is important to note that lists are implemented such that: +#### 列表复杂度 +我们在此考虑一些列表可用而元组不可用的改变序列的操作,如 `append`。请注意列表的实现导致: -- operations that add-to or remove-from the *end* of the list are $\mathcal{O}(1)$ -- operations that add-to or remove-from the *beginning* of the list are $\mathcal{O}(n)$ +- 在列表*结尾*添加或删除成员的操作为 $\mathcal{O}(1)$ +- 在列表*开头*添加或删除成员的操作为 $\mathcal{O}(n)$ -Let `my_list` represent a list of length $n$, and `i` is an integer drawn randomly from the interval $[0, n-1]$. The following is a summary of the complexities associated with various operations using a list (according to its implementation in CPython): +设 `my_list` 为长度为 $n$ 的列表,而 `i` 为从区间 $[0, n-1]$ 随意抽取的整数。以下为列表各种操作(在CPython实现中)的复杂度: -|Operation| Complexity | Explanation | +|操作| 复杂度 | 解释 | |---|---|---| -|`my_list[i] = obj`| O(1) | Set the ith entry of the list with a new object. | -|`my_list.append(obj)`| O(1) | Append a new object to the end of the list. | -|`my_list.pop()`| O(1) | Remove the object from the *end* of the list. | -|`my_list.pop(0)`| O(n) | Remove the object from the *beginning* of the list. | -|`my_list.sort()`| O(nlog(n)) | Return a sorted version of the list. | - +|`my_list[i] = obj`| O(1) | 将列表第i位的项目设为新对象。| +|`my_list.append(obj)`| O(1) | 在列表结尾添加新对象。| +|`my_list.pop()`| O(1) | 删除在列表*结尾*的对象。| +|`my_list.pop(0)`| O(n) | 删除在列表*开头*的对象。| +|`my_list.sort()`| O(nlog(n)) | 返回同列表的顺序版本。| diff --git a/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md b/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md index 5cc59ad..3c66f8f 100644 --- a/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md +++ b/Python/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.md @@ -4,67 +4,67 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Introduction to Sets, Difficulty: Medium, Category: Section :keywords: set, complexity, comparison, union, intersection, membership, hashing, lookup, interview preparation -``` + -# Data Structures (Part III): Sets & the Collections Module -## The "Set" Data Structure -The `set` type describes an *unordered* collection of *unique* objects. It is useful for: +# 数据结构(第三部分):集和集合模组 +## 集数据结构 +`set`(集)类是一个成员为*互不相同*的对象的*无序*集合。它在以下情况有用: -- Filtering out "repeat" objects in a collection, producing only its unique members. -- Quickly checking for membership, as a $\mathcal{O}(1)$ operation. -- Efficiently comparing two sets of objects; e.g. if one set is a "subset" of another. +- 过滤集合中“重复”的成员并仅仅返回其中不重复的成员。 +- 快速($\mathcal{O}(1)$)检查对象是否为成员。 +- 高效地对比两个集;如检查一个集是否为另外一个的“子集”(subset)。 -A set uses a "hashing" scheme for keeping track of its contents. Thus, like a dictionary's keys, a set can only store *immutable* objects so that its hashes will never become invalid. Unlike the other data structures that we have encountered, *there is no mechanism for retrieving an individual item from a set*. That is, there is no index or key that can be used to retrieve an individual member from a set. +集使用“哈希”(hashing)算法来记录它的成员。因此,像词典的键一样,集只能储存*不可变*的对象来保证对象的哈希值不会无效。和我们遇到的其它数据结构不同,*你无法从集中获取单独的成员*。也就是说,没有任何索引或键可以用来获取集中的单个成员。 -Python's sets also support many familiar set-algebra operations, like taking the union or intersection of sets, as we will see below. For an exhaustive listing of the functions available to sets, please consult [the official documentation on sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). +Python的集也支持了常见的集合代数操作,如并集(union)或交集(intersection)运算,如下所见。你可以阅读[集的官方说明文档](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)来查看所有可用的集函数。 -### Creating a set -You can initialize a set using the syntax: `{item1, item2, ...}`. Please note that this is distinct from the the dictionary-initialization syntax, which uses a colon to indicate key-value pairs: +### 创建集 +你可以用以下语法初始化集:`{item1, item2, ...}`。请注意,这和使用冒号表达键值对的词典初始化语法不同: ```python -# initializing a set containing various immutable objects +# 初始化有着各种不可变对象的集 >>> {1, 3.4, "apple", False, (1, 2, 3)} {False, 1, (1, 2, 3), 3.4, 'apple'} ``` -A set can be constructed using the generator-comprehension syntax: +你可以使用生成器理解语法来创建一个集: ```python -# initialization via set-comprehension +# 使用集理解来初始化 >>> {i**2 for i in range(5) if i != 3} {0, 1, 4, 16} ``` -And, like the `list`, `tuple`, and `dict` types, the `set` type can be used to construct a set from an iterable. Note that you must use `set()` if you want to create an empty set, using `{}` creates an empty *dictionary*: +同时,和 `list`,`tuple`,和 `dict` 类型类似,`set` 类型可以接受可迭代物来创建集。请注意你必须使用 `set()` 来创建一个空集,因为 `{}` 会创建一个空*词典*: ```python -# introducing the `set` type +# 介绍 `set` 类型 >>> type({2, 4, 6}) set -# using `set` to consume an iterable to construct a set +# 使用 `set` 消耗一个可迭代物来创建集 >>> set(range(4)) {0, 1, 2, 3} -# creating an empty set ->>> set() # specifying `{}` would create an empty *dictionary* +# 创建空集 +>>> set() # 如果使用 `{}` 则会创造一个*词典* set() ``` -Redundant items are "ignored" when constructing or adding to a set. Thus *constructing a set is a great way to extract the unique items from a collection*: +在创建或往集里面添加内容时会“无视”重复的项目。所以说,*创建集是一个很棒的从集合中抽取独特对象的方法*: ```python -# filter repeat-items from a collection by feeding it into a set +# 通过输入到集中过滤集合中重复的对象 >>> x = [1, 2, 1, 2, 1, "moo", "moo"] >>> set(x) {1, 2, 'moo'} @@ -73,94 +73,94 @@ Redundant items are "ignored" when constructing or adding to a set. Thus *constr
-**Reading Comprehension: Set Creation** +**阅读理解:创建集** -Use a set to find all of the unique letters in the string `"The cat in the hat"`. Ignore all non-letter characters and lowercase all letters. +使用集来找到字符串 `"The cat in the hat"` 中所有的独特的字母。无视所有不是字母的字符,并将所有字母小写化。
-### Set operations -Sets support membership-checking ($\mathcal{O}(1)$) along with iteration ($\mathcal{O}(n)$). Note that sets are unordered; thus the order of iteration is effectively random: +### 集操作 +集支持成员检测为($\mathcal{O}(1)$)以及迭代($\mathcal{O}(n)$)。注意集是无序的,所以迭代顺序实际上是随机的: ```python -# checking membership in a set +# 检查集成员 >>> 2 in {1, 2, 3} True -# iterating over a set (the order of iteration is random) +# 迭代集(迭代顺序是随机的) >>> [i for i in {"a", "b", "c"}] ['b', 'c', 'a'] ``` -Python also provides the set-theoretic operations of union, intersection, and the relations of set equality and set inclusion. These can be invoked using operator symbols or by calling functions on the set explicitly. +Python也支持集合代数操作:并集(union),交集(intersectino),等值(equality),和子集(subset)关系。你可以通过操作符或通过显性调用集函数来进行这些操作。 -For an exhaustive list of the functions available to the set, please [refer to the official Python documentation](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). +请[查阅Python官方说明文档](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)来阅读集函数的完整列表。 ```python -# demonstrating set-comparison operations +# 演示集对比操作 >>> x = {"a", "b", "c", "d"} >>> y = {"a", "b", "e"} -# union: items in x or y, or both ->>> x | y # or x.union(y) +# 并集:在x或y或全部两个集当中的项目 +>>> x | y # 等值于 x.union(y) {'a', 'b', 'c', 'd', 'e'} -# intersection: items in both x and y ->>> x & y # or x.intersection(y) +# 交集:在x和y中的项目 +>>> x & y # 等值于 x.intersection(y) {'a', 'b'} -# difference: items in x but not in y ->>> x - y # or x.difference(y) +# 差:在x而不在y中的项目 +>>> x - y # 等值于 x.difference(y) {'c', 'd'} -# symmetric difference: in x or y, but not in both ->>> x ^ y # or x.symmetric_difference +# 对称差:在x或y但不是全部两个的项目 +>>> x ^ y # 等值于 x.symmetric_difference(y) {'c', 'd', 'e'} -# check if set_1 is a superset of set_2 +# 检查set_1是否为set_2的超集(superset) >>> {1, 2, 3, 4} >= {1, 2} True -# check if set_1 and set_2 are equivalent sets +# 检查set_1和set_2是否为相同的集 >>> {1, 2, 3, 4} == {1, 2} False ``` -A set is a *mutable* object; it can be updated after it was created: +集是一个*可变*对象;你可以在创建后修改它: ```python -# sets are mutable +# 集是可变的 -# add a single member to `x` +# 往 `x` 中添加一个成员 >>> x.add("dog") -# update `x` by adding members of an iterable +# 通过添加可迭代物中的成员来更新 `x` >>> x.update([1, 2, 3]) -# remove a member of `x` +# 删除 `x` 的一个成员 >>> x.remove("a") >>> x {1, 2, 3, 'b', 'c', 'd', 'dog'} ``` -Because it is mutable, a set cannot be used as a dictionary-key, nor can a set be a member of another set. Python provides an immutable version of the set, `frozenset`, which has all of the functions of a set other than those that mutate the set: +因为集是可变的,它不能作为词典的键,也不能作为另外一个集的成员。Python提供了一个不可变版本的集,叫做 `frozenset`。它有着集所有除了修改集的操作函数: ```python -# `frozenset` is an immutable version of a Python set +# `frozenset` 是Python集的不可变版本 >>> frozenset(x) frozenset({1, 2, 3, 'b', 'c', 'd', 'dog'}) ```
-**Takeaway**: +**经验**: -Python's set is an unordered collection of unique, immutable objects. It is an excellent tool for extracting the unique members from a collection of items. The set provides $\mathcal{O}(1)$ membership-checking along with a suite of set-algebra operations for comparing sets. `frozenset` is an immutable version of the set. +Python的集的成员为互不相同,不可变的对象的集合。它是从对象集合中获取不重复的成员的好方法。集提供了 $\mathcal{O}(1)$ 的成员检测以及一组对比集的集合代数操作。`frozenset` 是集的不可变版本。
-**Reading Comprehension: Set Comparisons** +**阅读理解:对比集** -Given the enrollment lists for class-A and class-B, find the students enrolled in both classes. Produce the result as a sorted list of names. +设课A和课B的学生,寻找同时有着这两门课的同学名单。返回排序过的名字列表。 ```python >>> classA = ["Bohr", "Curie", "David", "Euler", "Fermi", "Feynman", "Gauss", "Heisenberg", "Noether"] @@ -170,30 +170,30 @@ Given the enrollment lists for class-A and class-B, find the students enrolled i
-## The Collections Module -Python provides a number of valuable, optimized data structures in its ["collections" module](https://docs.python.org/3/library/collections.html). It is recommended that the reader take some time to peruse this module. Here, we will briefly show off some of the utilities of its data structures. +## collections模组 +Python在其[“collections”模组](https://docs.python.org/3/library/collections.html)提供一系列优化过的实用数据结构。本文建议读者花一些时间去细读该模组。我们将在这里快速展示其中包含的数据结构的用处。 -Refer to the [official documentation](https://docs.python.org/3/library/collections.html) for a complete listing of the functions available to these data structures. +请查阅[官方说明文档](https://docs.python.org/3/library/collections.html)来阅读所有这些数据结构可用的函数。 ### Named-Tuple -A named tuple allows you to form a tuple whose members are named. Thus the user can access a member by name or via index. Otherwise the named tuple behaves just like a typical tuple. This facilitates clean, readable code. +一个命名元组(namedtuple)允许你创建有名字的成员的元组。这样,你可以通过名字或者索引来访问其中的成员。除此之外命名元组和正常元组的行为完全一样。这将帮助你编写干净易读的代码。 -Suppose, for instance, you want to keep track of the 3D-position and time of an event. You can use a named-tuple so that each space and time coordinate can be referenced "by name". In this way, the reader doesn't have to keep in mind that element-3 of your tuple corresponds to time: +比如说,假设你想要储存某事件的3D坐标以及时间,你可以使用命名元组来“根据名字”调用其空间和时间坐标。通过这个方式,代码的读者不需要记住元组的索引3代表着时间坐标这一设定: ```python -# demonstrate the use of named tuple +# 演示命名元组 >>> from collections import namedtuple -# Define a tuple that holds a space-time coordinate. -# Here we define the tuple to have four entries, named -# 'x', 'y', 'z', and 't', in order. +# 定义储存时空坐标的元组。 +# 我们如此顺序定义元组的四个成员,名字为 +# 'x','y','z',和 't'。 >>> space_time_coord = namedtuple("space_time_coord", ['x', 'y', 'z', 't']) -# `r` is a particular space-time coordinate (an instance of our named tuple) +# `r` 是某一个时空点(我们定义的命名元组的一个实例) >>> r = space_time_coord(1.5, 2.3, 5.1, 100.2) ->>> r.x # access the x coordinate "by name"; this is more descriptive than `r[0]` +>>> r.x # “通过名字”访问x坐标;这比 `r[0]` 更加易懂 1.5 >>> r.y @@ -205,7 +205,7 @@ Suppose, for instance, you want to keep track of the 3D-position and time of an >>> r.t 100.2 -# you can also access contents by indexing/slicing +# 你也可以通过索引/切片来访问其内容 >>> r[3] 100.2 @@ -215,52 +215,51 @@ Suppose, for instance, you want to keep track of the 3D-position and time of an -### Default Dictionary -A default dictionary allows you to specify a Python function, $f$ that will be used as a "default value" for that dictionary. The default value will be whatever $f()$ returns. That is, whenever you try to access a key that does not exist in the dictionary, instead of raising `KeyError`, the mapping $key \rightarrow f()$ will be created in the dictionary: +### 默认词典 +默认词典(defaultdict)允许你提供一个Python函数 $f$ 来作为该词典的“默认值”,其默认值为 $f()$ 返回的值。也就是说,每当你试图访问在词典中不存在的键时,词典会创建 $key \rightarrow f()$ 的对应关系而不会导致 `KeyError`: ```python -# demonstrate the behavior of the `defaultdict` +# 演示 `defaultdict` 的行为 >>> from collections import defaultdict ->>> example_default_dict = defaultdict(list) # will map any missing key to `list()` ->>> example_default_dict # an empty default dictionary +>>> example_default_dict = defaultdict(list) # 会将任何不存在的键对应到 `list()` +>>> example_default_dict # 空默认词典 defaultdict(list, {}) -# "apple" is not a key, so the default mapping "apple" -> list() is created -# and this value is returned +# "apple" 并不是一个存在的键,所以词典将创建默认对应关系 "apple" -> list() +# 并返回对应的值 >>> example_default_dict["apple"] [] -# this mapping now exists in the dictionary ->>> example_default_dict +# 现在这个对应关系在词典中存在 +>>> example_default_dict defaultdict(list, {'apple': []}) ``` -Suppose you want to use a dictionary as a grade book, which maps $name \rightarrow grades$. With a standard dictionary, you have to worry about encountering a student for the first time: +假设你想要将一个词典当作成绩簿来使用,其对应关系为 $名字 \rightarrow 成绩(多个)$。在使用标准词典时,你会需要担心第一次输入某学生成绩的情况: ```python -# using a vanilla dictionary to store: name -> list of grades -student = "Ryan" -grade = 52 # I failed the test... +# 使用标准词典来储存:名字 -> 成绩列表 +student = "Ryan" # 译者注:这是原作者的名字 +grade = 52 # 我不合格... -# standard dictionary usage +# 标准词典的用法 gradebook = {} -# if student isn't in the gradebook, enter that student -# along with an empty list as the grades +# 如果学生不在成绩簿中,将学生先作为空列表输入 if student not in gradebook: gradebook[student] = [] -gradebook[student].append(grade) # append the grade to that student's list of grades +gradebook[student].append(grade) # 在列表最后添加学生的成绩 ``` -The default dictionary's behavior exactly accommodates this initialization process (when providing `list` as the initialization function): +默认词典的行为(当你向初始化函数提供 `list` 时)完全代替了以上的初始化过程: ```python -# using a default dictionary to store: name -> list of grades +# 使用默认词典来储存:名字 -> 成绩列表 >>> gradebook = defaultdict(list) -# Because "Susan" doesn't exist in the dictionary -# `list()` creates an empty list, as a default value, -# which we can immediately append her grade to +# 因为 "Susan" 在词典中并不存在 +# `list()` 创建一个空列表来作为默认值 +# 然后我们可以立刻向其添加她的成绩 >>> gradebook["Susan"].append(84) >>> gradebook @@ -269,58 +268,58 @@ defaultdict(list, {'Susan': [84]}) -### Counter -Python's counter data structure is designed for tallying the unique objects that it encounters. It essentially creates a dictionary that maps: $obj \rightarrow count$. Suppose you want to study the distribution of words used in a body of text; counter is perfect for this application: +### 计数器 +Python的计数器(counter)数据结构旨在计算它遇到的独特的对象数。基本上,它就是创建了一个对应 $对象 \rightarrow 遭遇次数$ 的词典。假设你想要了解在某文本中单词的分布,计数器是完美的解决方案: ```python -# demonstrate the `Counter` data structure +# 演示 `Counter` 数据结构 >>> from collections import Counter -# Note: We will "normalize" our text by making it all lowercase. -# We will then split the string by its spaces, storing the resulting -# tokens in a list. For real text, we would also want to remove punctuation +# 注:我们将会“标准化“我们的文本,使其全部都为小写。 +# 我们将会根据空格区分单个单词,并将得到的单词存在列表中 +# 如果我们在使用真正的文本,我们也会想要删除标点符号 >>> text_1 = "The cat in the hat" >>> text_1 = text_1.lower().split() >>> text_1 ['the', 'cat', 'in', 'the', 'hat'] ->>> word_distr = Counter(text_1) # tally the unique objects in `text_1` +>>> word_distr = Counter(text_1) # 数 `text_1` 中独特对象的出现次数 >>> word_distr Counter({'cat': 1, 'hat': 1, 'in': 1, 'the': 2}) -# feed additional items to the counter by "update" +# 利用“update”来输入更多的对象 >>> text_2 = "The apple in the tree" >>> text_2 = text_2.lower().split() >>> word_distr.update(text_2) >>> word_distr Counter({'apple': 1, 'cat': 1, 'hat': 1, 'in': 2, 'the': 4, 'tree': 1}) -# get the top-2 most common words, along with their counts +# 获取2个最常见的单词以及它们的出现次数 >>> word_distr.most_common(2) [('the', 4), ('in', 2)] -# get the count for the word "tree" +# 获取单词“tree”的出现次数 >>> word_distr["tree"] 1 ``` -`Counter` accepts any iterable of immutable objects: +`Counter` 接受任何成员为不可变对象的可迭代物: ```python >>> Counter([0, 0, "moo", (None, None), (None, None), (None, None)]) Counter({(None, None): 3, 0: 2, 'moo': 1}) ``` -Refer to the [official documentation](https://docs.python.org/3/library/collections.html#counter-objects) for a complete listing of all the nice functions that `Counter` has access to. +请查阅[官方说明文档](https://docs.python.org/3/library/collections.html#counter-objects)来阅读 `Counter` 的棒棒的可用函数。 -### The deque -Like the list, Python's deque is a mutable, sequential data structure. What distinguishes the deque is that: +### 双队列 +像列表一样,Python的双队列(deque)是一个可变的序列性数据结构。双队列不同的点在于: - - Mutating either the beginning or the end of a deque is $\mathcal{O}(1)$, whereas mutating the beginning of a list is $\mathcal{O}(n)$. As such, the deque has unique functions to take advantage of this, like `appendleft`. - - The downside of the preceding feature is that *accessing items near the middle of the deque is* $\mathcal{O}(n)$, whereas it is $\mathcal{O}(1)$ for lists and tuples. + - 修改双队列的开头或者结尾都是 $\mathcal{O}(1)$,而修改列表开头是 $\mathcal{O}(n)$。因此,双队列有着独特的函数来利用这一优势,如 `appendleft`。 + - 以上功能的坏处在于*获取双队列靠近中间的对象是* $\mathcal{O}(n)$,而列表和元组是 $\mathcal{O}(1)$。 -A complete rundown of the deque's functionality can be found [here](https://docs.python.org/3/library/collections.html#deque-objects). +你可以在[这里](https://docs.python.org/3/library/collections.html#deque-objects)找到双列表的完整功能。 -The deque is included in Python's `collections` module, and thus must be imported: +双列表属于Python `collections` 模组的成员,因此你需要导入它: ```python >>> from collections import deque >>> my_deque = deque([1,2,3]) @@ -330,21 +329,21 @@ deque([0, 1, 2, 3]) ``` -## Links to Official Documentation +## 官方说明文档链接 -- [Sets and frozen sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset) - - [Tutorial on sets](https://docs.python.org/3/tutorial/datastructures.html#sets) -- [The collections module](https://docs.python.org/3/library/collections.html) +- [集和冻集](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset) + - [集教程](https://docs.python.org/3/tutorial/datastructures.html#sets) +- [collections模组](https://docs.python.org/3/library/collections.html) -## Reading Comprehension Solutions +## 阅读理解答案 -**Set Creation: Solution** +**创建集:解** -Use a set to find all of the unique letters in the string `"The cat in the hat"`. Ignore all non-letter characters and lowercase all letters. +使用集来找到字符串 `"The cat in the hat"` 中所有的独特的字母。无视所有不是字母的字符,并将所有字母小写化。 -We can use the built-in string functions [isalpha](https://docs.python.org/3/library/stdtypes.html#str.isalpha) and [lower](https://docs.python.org/3/library/stdtypes.html#str.lower) to filter out non-letter characters, and to lowercase the letters. +我们可以使用内置的字符串函数[isalpha](https://docs.python.org/3/library/stdtypes.html#str.isalpha)和[lower](https://docs.python.org/3/library/stdtypes.html#str.lower)来过滤非字母字符并小写化所有字母。 ```python >>> sentence = "The cat in the hat" @@ -354,15 +353,15 @@ We can use the built-in string functions [isalpha](https://docs.python.org/3/lib -**Set Comparisons: Solution** +**对比集:解** -Given the roster for class-A and class-B, find the students enrolled in both classes. Produce the result as a sorted list. +根据课A和课B的名单表,找到同时在两个班的学生名单。返回排序过的名字列表。 ```python >>> classA = ["Bohr", "Curie", "David", "Euler", "Gauss", "Heisenberg", "Noether"] >>> classB = ["Bohm", "Bohr", "Einstein", "Fermi", "Gauss", "Hopper", "Montalcini"] ``` -We can find the entries common to both lists by constructing sets from them, and then taking the intersection of those sets. The result is a set, which is an iterable. Thus it can be fed to the built-in function [sorted](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#Functions-that-act-on-iterables), to produce a sorted list of names. +我们可以通过使用这两个列表创建集然后求交集来找出两个列表通用的名字。结果为一个集,而集是一种可迭代物。因此我们可以将其输入进内置的函数[sorted](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#操作可迭代物的函数)并返回排序过的名字列表。 ```python >>> sorted(set(classA) & set(classB)) diff --git a/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md b/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md index 5333500..d74dbb4 100644 --- a/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md +++ b/Python/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.md @@ -4,116 +4,116 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Introduction to Dictionaries, Difficulty: Medium, Category: Section :keywords: dictionary, complexity, key, value, iteration, get item, hashing, lookup, interview preparation -``` + -# Data Structures (Part II): Dictionaries -Python's dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects. **Each key must map to exactly one value**, meaning that a key must be unique. +# 数据结构(第二部分):词典 +Python的词典(dictionary)允许你储存键值对(key-value pair),然后通过提供键来快速地获取其对应的值。具体来讲,你通过描述从键到值的单向对应关系来创建词典。**每个键应该只对应一个值**,也就是说每个键都应该是唯一的。 -Let's create the following mapping of grocery-to-price: +让我们来创建以下从食物到价格的对应关系: -- "cheese" $\rightarrow$ 2.53, -- "milk" $\rightarrow$ 3.40, +- "cheese" $\rightarrow$ 2.53, +- "milk" $\rightarrow$ 3.40, - "frozen pizza" $\rightarrow$ 8.01 ```python -# use a dictionary to map groceries to prices: item-name -> price +# 使用一个词典来将食物来对应价格:名字 -> 价格 >>> items_to_prices = {"cheese": 2.53, "milk": 3.40, "frozen pizza": 8.01} -# looking up the price of "frozen pizza" +# 查看 "frozen pizza" 的价格 >>> items_to_prices["frozen pizza"] 8.01 ``` -Python's dictionary is a shining star among its data structures; it is compact, fast, versatile, and extremely useful. It can be used to create a wide variety of mappings. +Python的词典是其数据结构中一颗闪耀的星;它紧凑,高效,通用,并非常有用。你可以用它来创建多种多样的对应关系。 ```python -# keep track of whether or not a 3D coordinate fell into some region in space -# map (x, y, z) coordinates to "is in a region": (x, y, z) -> True/False +# 记录某3D坐标是否处于空间中某区域之中 +# 将 (x, y, z) 坐标对应到“是否在区域中”:(x, y, z) -> True/False >>> point_to_region = {(0.1, 2.2, 3):False, (-10., 0, 4.5):True, (4.3, 1.0, 9.5):False} >>> point_to_region[(-10., 0, 4.5)] True -# map student-name to exam scores: name -> scores +# 将学生名字对应到考试成绩中:名字 -> 成绩 >>> name_to_scores = {"Ryan S": [65, 50, 80], "Nick S": [100, 99, 90]} >>> name_to_scores["Ryan S"] [65, 50, 80] ``` - It is important to note outright that the time it takes for dictionary to take a key and retrieve a value *does not depend on the size of the dictionary.* That is the complexity for a dictionary look-up is $\mathcal{O}(1)$! It accomplishes this by making use of a technique known as [hashing](https://en.wikipedia.org/wiki/Hash_function). +我们应该立刻指出:在词典中查找某键对应的值的速度*并不会根据词典大小改变。*也就是说,词典查找的复杂度为 $\mathcal{O}(1)$!它通过一个知名的[哈希算法](https://en.wikipedia.org/wiki/Hash_function)技巧来达到这一点。 -These are all instances of the built-in `dict` type: +以下为所有内置 `dict` 类型的实例: ```python >>> type(items_to_prices) dict ``` -We will be discussing the essentials of the dictionary. It is highly recommended that you refer to the official Python documentation for a [complete rundown of all the functions available to the dictionary](https://docs.python.org/3/library/stdtypes.html#dict). +我们会在下文讨论词典的基础。本文强烈建议你阅读Python官方说明文档来查看[所有词典可用的函数](https://docs.python.org/3/library/stdtypes.html#dict). -## Dictionary Basics -### Constructing a dictionary -A nice syntax for creating a dictionary is to specify key-value pairs inside "curly braces": `{key1:value1, key2:value2, ...}`. As an example, let's construct a dictionary that maps types of foods to "fruit" or "vegetable". We'll start by mapping "apple" to "fruit", and "carrot" to "vegetable" +## 词典基础 +### 创建词典 +你可以通过在“花括号”中输入键值对来创建词典:`{key1:value1, key2:value2, ...}`。作为范例,让我们创建一个将食物名字对应到 "fruit" 或 "vegetable" 的词典吧。我们首先将 "apple" 对应到 "fruit","carrot" 对应到 "vegetable" ```python -# use `{key1:value1, key2:value2, ...} to create a dictionary that maps: +# 使用 `{key1:value1, key2:value2, ...}` 来创建词典: # "apple" -> "fruit" # "carrot" -> "vegetable ->>> fruit_or_veggie = {"apple":"fruit", "carrot":"vegetable"} +>>> fruit_or_veggie = {"apple":"fruit", "carrot":"vegetable"} -# create an empty dictionary +# 创建空词典 >>> {} {} ``` -You can also use `dict` as a constructor to create the dictionary. It can be fed an iterable of key-value pairs, each of which is packed in a sequence, such as a tuple. +你也可以使用 `dict` 来作为构造器来创建词典。你可以向其输入存有键值对(键值对由如元组的序列表达)的可迭代物。 ```python -# use `dict` to create a dictionary that maps: +# 使用 `dict` 来创建词典: # "apple" -> "fruit" # "carrot" -> "vegetable >>> fruit_or_veggie = dict([("apple", "fruit"), ("carrot", "vegetable")]) -# use `dict` to create an empty dictionary: +# 使用 `dict` 来创建空词典 >>> dict() {} ``` -Lastly, Python also supports a dictionary-comprehension syntax, which mirrors the generator/list comprehension syntax covered earlier in this module: +最后,Python也支持词典理解语法,其与本模组之前讨论的生成器/列表理解语法类似: ``` {key:value for key, value in [if bool()]} ``` ```python -# use the 'dictionary comprehension' syntax to create a dictionary that maps: +# 使用“词典理解”语法来创建词典 # "apple" -> "fruit" # "carrot" -> "vegetable >>> {k:v for k,v in [("apple", "fruit"), ("carrot", "vegetable")]} {'apple': 'fruit', 'carrot': 'vegetable'} ``` -### Retrieving a value, given a key -Now we can use this dictionary to "look up" if an item is a fruit or a veggie. Dictionaries support the same square-bracket "get-item" syntax as a list/tuple, but here a valid key is used as the index: +### 返回键对应的值 +现在我们可以使用词典来“查找”某项目是水果还是蔬菜。词典支持和列表/元组一样的方括号“获取项目”语法,但与其使用索引我们将使用一个合法的键: ```python -# get the value associated with the key "apple" +# 获取键 "apple" 对应的值 >>> fruit_or_veggie["apple"] "fruit" ``` -`KeyError` will be raised if you try to look-up a key that doesn't exist: +尝试查找不存在的键会导致 `KeyError`: ```python -# "grape" hasn't been specified as a key +# "grape" 并没有作为键被定义 >>> fruit_or_veggie["grape"] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) @@ -123,19 +123,19 @@ KeyError Traceback (most recent call last) KeyError: 'grape' ``` -### Adding more key-value mappings -Once created, a dictionary can have a new key-value pair be "set" using `my_dict[new_key] = new_value`: +### 添加额外的键值对 +在词典创建后,你可以通过 `my_dict[new_key] = new_value` 在其中设定额外的的键值对: ```python -# set the mapping "banana" -> "fruit" +# 设定对应 "banana" -> "fruit" >>> fruit_or_veggie["banana"] = "fruit" >>> fruit_or_veggie {'apple': 'fruit', 'banana': 'fruit', 'carrot': 'vegetable'} ``` -If the key already exists, the mapping for that key will simply be updated. +如果键已经存在的话,那该键对应的值将被更新。 -The `update` function can be used to add multiple key-value pairs at once. This function can be passed another dictionary or an iterable of key-value sequences +你可以使用 `update` 函数来一次性添加多个键值对。该函数接受另外一个词典或成员为键值对序列的可迭代物 ```python -# adding multiple key-value pairs to the dictionary +# 向词典添加多个键值对 >>> fruit_or_veggie.update([("grape", "fruit"), ("onion", "vegetable")]) >>> fruit_or_veggie {'apple': 'fruit', @@ -148,19 +148,20 @@ The `update` function can be used to add multiple key-value pairs at once. This
-**Reading Comprehension: Dictionary Basics** +**阅读理解:词典基础** + +设含有学生名的元组 `("Ashley", "David", "Edward", "Zoe")` 以及他们对应的考试成绩 `(0.92, 0.72, 0.88, 0.77)`,创建一个词典来对应:名字 $\rightarrow$ 成绩。然后,将Zoe的成绩更新为 `.79`。最后添加一个新学生Ryan,其成绩为0.34。 -Given the tuple of student names `("Ashley", "David", "Edward", "Zoe")`, and their corresponding exam grades `(0.92, 0.72, 0.88, 0.77)`, create a dictionary that maps: name $\rightarrow$ grade. Then, update Zoe's grade to `.79`. Lastly, add a new student, Ryan, whose grade is 0.34. +译者注:原作者名为Ryan,是位自黑达人。
-## What Can a Dictionary Store? -Although the preceding example only involves a mappings from strings to strings, *the keys and values of a dictionary can be heterogeneous in type*: +## 词典可以储存什么? +虽然前文的例子中仅仅将字符串对应字符串,但是*词典的键和值的类型可以相异*: ```python -# demonstrates the wide variety of object types that can be used as -# keys and values in a dictionary +# 演示词典可以使用的多种多样的键值类型 >>> example_dict = {-1:10, "moo":True, (1, 2):print, 3.4:"cow", False:[]} >>> example_dict[-1] 10 @@ -178,32 +179,32 @@ True [] ``` -To be specific, a dictionary's contents are dictated by the following rules: +具体来讲,词典应遵循以下规则: -- A dictionary *key* must be an *immutable* object (more precisely, it must be [hashable](https://docs.python.org/3/glossary.html#term-hashable); don't worry about this detail). -- A dictionary *value* can be any object (even the dictionary itself! Try this, it's cool!) +- 词典的*键*必须是*不可变*的对象(更加精确地讲,它必须是[可哈希](https://docs.python.org/3/glossary.html#term-hashable)(hashable)的;不要太在意这个细节)。 +- 词典的*值*可以是任何对象(甚至可以是同一个词典!试试看,这挺酷的!)
-**Recall**: +**回忆**: -A mutable object can be changed after it is created. An immutable object cannot be changed. +可变对象在被创建后是可以被修改的。不可变对象则不能被修改。
-Thus valid keys can be the following types: +所以合法的键可以是以下类型: + + - 数字(整数,浮点数,复数) + - 字符串 + - 元组(但元组中的成员也必须是不可变对象) + - 布尔值 + - [冻集](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#集操作)(frozenset)对象 + +使用可变对象作为键的问题在于该对象在作为键使用*之后*可以被改变。因此,词典会需要通过某种方法“检测”到这个变化并为变化后的键重新创建它的“查找方式”。相比之下,值可以是可变对象,因为值对象的细节并不影响词典如何查找该值。 - - numbers (integers, floating-point numbers, complex numbers) - - strings - - tuples (if the tuple contains anything, it must be other immutable objects) - - boolean values - - [frozenset](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#Set-operations) objects - -Trying to use a mutable object as a key is problematic since that object could be changed *after* it was already used as a key. Thus the dictionary would have to "detect" this change and recreate its "lookup scheme" for the changed key. Values, on the other hand, can be mutable because the details of a given value-object have no impact on how the dictionary retrieves it. - -In accordance with this discussion will get a `TypeError` if you try to use a list as a key, since lists are mutable: +如上所述,如果你试图使用列表来作为键,你会收到一个 `TypeError`,因为列表是可变的: ```python -# trying to use a list as a key -# this raises an error because lists are mutable +# 试图将列表作为键使用 +# 因为列表是可变的,这会报错 >>> bad_dict = {[]:1} --------------------------------------------------------------------------- TypeError Traceback (most recent call last) @@ -213,25 +214,24 @@ TypeError Traceback (most recent call last) TypeError: unhashable type: 'list' ``` -### Numerical Precision & Dictionary Keys -Care must be taken when using floating-point numbers as a key in a dictionary, [due to its limited numerical precision](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Understanding-Numerical-Precision). For the same reason that you ought not rely on two floats being equal, you should not assume that two floats will produce the same hash, when stored as a key: +### 数字精度和词典键 +在使用浮点数作为词典键时需小心,因为浮点数的[精度有限](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#理解数字精度)。和你不应该检查两个浮点数是否完全相同的原因一样,你不能保证两个浮点数作为键时会有相同的哈希值: ```python -# the folly of using a floating-point number as a key -# in a dictionary +# 将浮点数作为词典键使用导致的尴尬情况 >>> x = {} >>> x[(0.1 + 0.1 + 0.1) - 0.3] = "apple" >>> x[0.0] KeyError: 0 ``` -An acceptable way of accommodating the use of a float as a key, depending on the use case, is to first round the floating point number to normalize it to a lower precision: +根据使用情况,一种可以接受的使用浮点数作为值的方法是先将浮点数四舍五入到一个更低的精度: ```python -# rounding a float before using it as a key +# 现将浮点数四舍五入再将其用为键 >>> x = {} -# round the float to its 2nd decimal place +# 将浮点数四舍五入到小数点后第二位 >>> float_key = round((0.1 + 0.1 + 0.1) - 0.3, 2) >>> x[float_key] = "apple" >> x[0.0] @@ -240,78 +240,78 @@ An acceptable way of accommodating the use of a float as a key, depending on the
-**Takeaway**: +**经验**: -A dictionary key must be an immutable object. A dictionary value can be any object. +词典的键必须是不可变对象。词典的值可以是任何对象。
-### Inspecting a Dictionary -The dictionary provides tooling for inspecting and iterating over its keys and values. We will use the following dictionary for our examples: +### 检查词典 +词典提供了一些检查和迭代其键和值的工具。我们在范例中将会使用以下词典: ```python >>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"} ``` -**Inspecting a dictionary's keys** +**检查词典的键** -The dictionary itself can be used to iterate over its keys: +你可以直接使用词典本身来迭代它的键: ```python -# iterating over a dictionary produces its keys +# 迭代词典会迭代它的键 >>> [i for i in example_dict] ['key1', 'key2', 'key3'] ``` -You can also use the dictionary to test for membership among its keys: +你也可以使用词典本身来检测某对象是否为它的键: ```python -# checking if an object is among a dictionary's keys +# 检查某对象是否是词典的键 >>> "key3" in example_dict True -# you *cannot* use this to check for membership among its valus +# 你*不能*用这个方法检查词典的值 >>> "value3" in example_dict False ``` -`len` counts the number of keys in the dictionary: +`len` 会返回词典有多少个键: ```python >>> len(example_dict) 3 ``` -`example_dict.keys()` also returns an iterable over the dictionary's keys, and thus can be used to exactly the same effect as the dictionary itself in these preceding examples. +`example_dict.keys()` 也会返回一个词典键的可迭代物。因此它可以达到和之前范例直接使用词典一样的效果。 -**Inspecting a dictionary's values** +**检查词典的值** -`example_dict.values()` can be iterated over to produce that dictionary's values: +迭代 `example_dict.values()` 会提供词典的值: ```python -# iterating over a dictionary's values +# 迭代词典的值 >>> [i for i in example_dict.values()] ['value1', 'value2', 'value3'] ``` -You can also use this to test for membership among the dictionary's values: +你也可以使用这个函数来检查某对象是否为词典的值: ```python -# checking if an object is among a dictionary's values +# 检查某对象是否为词典的值 >>> "value1" in example_dict.values() True ``` -**Inspecting a dictionary's key-value pairs** +**检查词典的键值对** -`example_dict.items()` can be iterated over to produce that dictionary's key-value pairs (which are packed into tuples): +迭代 `example_dict.items()` 会返回词典的键值对(它们被打包在元组中): ```python -# iterating over a dictionary produces its keys +# 迭代词典的items会返回它的键值对 >>> [i for i in example_dict.items()] [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')] ``` -You can also use this to test for membership among the dictionary's key-value pairs: +你也可以用这个函数来检测某对象是否为词典的键值对: ```python -# checking if a key-value pair exists in a dictionary +# 检查某对象是否为词典的键值对 >>> ('key1', 'value1') in example_dict.items() True ``` @@ -319,52 +319,52 @@ True
-**Reading Comprehension: Inverting a Dictionary** +**阅读理解:反向词典** -Write a function that inverts a dictionary. For example, if you were given `x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}`, you would produce the dictionary `inverted_x = {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}`. +编写一个函数来将词典反向。比如说,如果函数收到 `x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}`,那你应返回词典 `inverted_x = {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}`。
-**Reading Comprehension: Inspecting a Dictionary** +**阅读理解:检查词典** -Assume we are working with a dictionary whose values are all *unique* numbers. Write a function that returns the *key* that maps to the *largest* value in the dictionary. +假设我们收到一个值为*互不相同*的数字的词典,编写一个返回对应词典中*最大*值的*键*的函数。 -Next, generalize your solution for a dictionary whose values are not necessarily unique. Return a tuple of all of the keys that map to that max value. +然后,修改你的函数来处理值可能重复值的词典。返回包含所有对应最大值的键的元组。
-### Time Complexities of the Dictionary's Functions -In addition to being flexible and versatile, the dictionary's functions manage to be quite efficient as well. The following is a summary of the time complexities associated with various common operations using a dictionary (according to its implementation in CPython) - note all the $\mathcal{O}(1)$ operations! +### 词典函数的时间复杂性 +除了灵活和通用之外,词典的函数也相对高效。以下为词典常见操作(在CPython实现中)的时间复杂性——请注意 $\mathcal{O}(1)$ 操作的数量! -Let `example_dict` represent a dictionary with $n$ key-value pair mappings. +设 `example_dict` 为有 $n$ 个键值对的词典。 -The following are $\mathcal{O}(1)$ operations: +以下为 $\mathcal{O}(1)$ 的操作: -- Return the number of keys in the dictionary: `len(example_dict)` -- Check if the key is in the dictionary, and return the value if it is: `example_dict[key]` -- Set a key-value mapping: `example_dict[key] = value` -- Check if an object is among the dictionary's keys: `obj in example_dict` -- Check if a pair of objects are among the dictionary's key-value pairs: `(obj1, obj2) in example_dict.items()` +- 返回词典键的数量:`len(example_dict)` +- 检查某对象是否为词典的键,如果是的话返回它对应的值:`example_dict[key]` +- 设定一个键值对:`example_dict[key] = value` +- 检查某对象是否为词典的键:`obj in example_dict` +- 检查某对对象是否为词典的键值对:`(obj1, obj2) in example_dict.items()` -The following are $\mathcal{O}(n)$ operations: +以下为 $\mathcal{O}(n)$ 的操作: -- Check if an object is among the dictionary's values: `obj in example_dict.values()` -- Iterate over the dictionary's keys/values/key-value pairs +- 检查某对象是否为词典的值:`obj in example_dict.values()` +- 迭代词典所有的键/值/键值对 -### Are Dictionaries Ordered? A Word of Warning -Unlike Python's sequences, the dictionary has no inherent ordering... that is, until Python 3.6 came out. +### 词典是否有序?一句警告 +和Python的序列不同的是,词典没有任何内在的顺序...但是这是在Python 3.6前的历史了。 -Prior to Python 3.6, a dictionary had no ordering associated with it. If you iterated over a dictionary's keys, values, or key-value pairs, you had no guarantee about the *order* in which these items would be produced. `[i for i in example_dict]` could produce a list of keys with different ordering each time the code was run; you were only guaranteed that the list would contain all of the dictionary's keys: +在Python 3.6之前,词典并没有任何顺序。如果你迭代一个词典的键,值,或键值对,你不会得到任何*顺序*的保证。`[i for i in example_dict]` 可能在每次运行时返回顺序不同的键列表;你唯一得到的保证是列表会包含词典所有的键: ```python -# in Python 3.5 and earlier, dictionaries were unordered +# 在Python 3.5和之前,词典是无序的 >>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"} -# this can produce lists with different orders +# 这可能会返回排序不同的列表 >>> [i for i in example_dict] ["key1", "key3", "key2"] @@ -377,65 +377,63 @@ Prior to Python 3.6, a dictionary had no ordering associated with it. If you ite ... ``` -The dictionary was [reimplemented in Python 3.6](https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation) so that it will consume roughly 25% less memory than before (which is a big deal!). The catch is that this new implementation entails that the dictionary's various iterables (e.g. `dict.keys()`, `dict.values()`, `dict.items()`) will always yield their items according to the order in which they were added to the dictionary. +词典在[Python 3.6中重新实现](https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation),使得它相比以前会少用大约25%的内存(这是一个很大的提升!)。随之而来的变化就是新的实现导致了词典的各种可迭代物(如 `dict.keys()`,`dict.values()`,`dict.items()`)每次都会根据添加到词典中的顺序返回对象。 ```python -# in Python 3.6 and beyond dictionaries are ordered according to the order in -# which key-value pairs were added to the dictionary by the user +# 在Python 3.6和之后,词典根据键值对添加的顺序来排序 >>> example_dict = {"key1":"value1", "key2":"value2", "key3":"value3"} -# this will always produce the same ordering of keys +# 这永远都会返回一样顺序的键 >>> [i for i in example_dict] ["key1", "key2", "key3"] ``` -This is great, right? Wrong! If you write code in Python 3.6 that relies on the fact that dictionaries are ordered, your algorithm will almost certainly produce the wrong results if you run it using Python 3.5 or earlier! Worst of all, it very unlikely that this will raise any error in your code so the bug will persist silently - this is very tough to catch! +这很棒,对吧?不对!如果你在Python 3.6中编写基于词典成员顺序的代码,那么你的算法在Python 3.5和以前几乎一定会导致错误的结果!最差的一点是,这很可能在你的代码中根本不报错,所以这个bug会静默地持续下去——这很难抓到! -**Unless you make explicit that your code is incompatible with versions of Python prior to Python 3.6, write your code as if the dictionary is unordered!** +**如果你没有明显标记你的代码和Python 3.6之前的版本不兼容,编写代码的时候假装词典并没有顺序!** -If you do want to use an ordered dictionary, make use of `collections.OrderedDict`, which behaves like just like the standard dictionary but is guaranteed to maintain ordering regardless of what version of Python you are using. +如果你真的想要需要一个顺序的词典,使用 `collections.OrderedDict`。它的行为和正常的词典一模一样,但它不管在什么Python版本都保证成员顺序。 ```python from collections import OrderedDict >>> ordered = OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]) -# this will always produce the same result, regardless of what -# version of Python is being used +# 这永远都会返回相同的结果,不论Python版本 >>> [i for i in ordered] ["key1", "key2", "key3"] ```
-**Takeaway**: +**经验**: -No matter what version of Python you are using, write your code as if the Python dictionary is unordered. If you do want to use an ordered dictionary, your code should make use of `collections.OrderedDict`. +不管你在用什么Python版本,在编写代码的时候假装Python词典是无序的。如果你真的想要一个有序的词典,你的代码应该使用 `collections.OrderedDict`。
-## Links to Official Documentation +## 官方说明文档链接 -- [Dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) - - [Dictionaries tutorial](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) -- [Definition of 'hashable'](https://docs.python.org/3/glossary.html#term-hashable) -- [Dictionary view objects](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects) +- [词典](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) + - [词典教程](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) +- [“可哈希”的定义](https://docs.python.org/3/glossary.html#term-hashable) +- [词典视阈对象](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects)(dictionary view objects) -## Reading Comprehension Solutions +## 阅读理解答案 -**Dictionary Basics: Solutions** +**词典基础:解** -Given the tuple of student names `(Ashley, David, Edward, Zoe)`, and their corresponding exam grades `(0.92, 0.72, 0.88, 0.77)`, create a dictionary that maps: name $\rightarrow$ grade. +设包含学生名字的元组 `(Ashley, David, Edward, Zoe)` 以及对应的成绩 `(0.92, 0.72, 0.88, 0.77)`,创建一个词典:name $\rightarrow$ grade。 -Then, update Zoe's grade to `.79`. Lastly, add a new student, Ryan, whose grade is 0.34. +然后,将Zoe的成绩更新为 `.79`。最后,添加一个新学生Ryan,其成绩为 0.34。 ```python names = ("Ashley", "David", "Edward", "Zoe") scores = (0.92, 0.72, 0.88, 0.77) ``` -Here is a basic, but verbose solution. It is too long and its logic is complicated by the use of `index`. +这是一个简单但冗长的解法。它太长,且其逻辑使因为使用了 `index` 而没必要地复杂化了。 ```python # basic solution for creating `grades` @@ -446,24 +444,24 @@ for index in range(len(names)): grades[name] = value ``` -You should make use of the function [zip](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Itertools.html#zip) to pair the names and scores together in an iterable, and create the dictionary using a comprehension expression. +你应该使用函数[zip](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Itertools.html#zip)来将名字和成绩打包到一个可迭代物中,并利用理解表达式来创建词典。 ```python -# much better solution for creating `grades` +# 好很多的创建 `grades` 的方式 grades = {student:value for student, value in zip(names, scores)} -# updating Zoe's grade +# 更新Zoe的成绩 grades["Zoe"] = 0.79 -# adding Ryan's grade +# 添加Ryan的成绩 grades["Ryan"] = 0.34 ``` -**Inverting a Dictionary: Solution** +**反向词典:解** ```python -# simple solution: using a for-loop +# 简单解:使用for循环 x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} inverted_x = {} for key, value in x.items(): @@ -471,21 +469,21 @@ for key, value in x.items(): ``` ```python -# better solution: using a dictionary-comprehension +# 更好的解:使用词典理解 inverted_x = {value:key for key, value in x.items()} ``` -**Inspecting a Dictionary: Solution** +**检查词典:解** -Assume we are working with a dictionary whose values are all *unique* numbers. Write a function that returns the key that maps to the *largest* value in the dictionary. +假设我们收到一个值为*互不相同*的数字的词典,编写一个返回对应词典中*最大*值的键的函数。 -The solution that you should be able to arrive at is: +你应该能够写出的解为: ```python # solution -def max_key(x): +def max_key(x): max_val = max(x.values()) for key, value in x.items(): if value == max_val: @@ -496,12 +494,12 @@ def max_key(x): 'c' ``` -The downside of this is that it iterates over `x` twice: once via `max` and once via the for-loop. The optimal solution for this only involves a single iteration, however it requires advanced concepts that are beyond the scope of the material presented here. We include the ideal solution for posterity: +这个函数的不利之处在于它迭代了 `x` 两次;一次由 `max`,一次由for循环。这个问题的最优解仅仅迭代一次,但它用到了在超出本节纲领的进阶概念。我们在此为未来的你提供最优解: -You can provide the `max` function with "key" argument, which accepts the function that should be used to evaluate the "value" for each iteration, which is used to discern the max element. Here, we pass it the built-in dictionary-function [get](https://docs.python.org/3/library/stdtypes.html#dict.get), which takes in a dictionary's key as an argument, and returns the corresponding value from the mapping. Thus `max` will iterate over each key of `x`, and discern the maximum value by comparing the value returned by each `x.get(key)` (which is effectively the same as `x[key]`). +你可以为 `max` 函数提供“key”参数。这个参数接受用来计算每轮迭代的“值”的函数,而这个值就是 `max` 函数用来找出最大成员的使用的值。在此,我们向其输入内置的词典函数[get](https://docs.python.org/3/library/stdtypes.html#dict.get)。它接受词典的键为参数并返回对应的值。所以 `max` 会迭代 `x` 的每一个值并通过对比每个 `x.get(key)`(这和 `x[key]` 功能基本一样)来寻找最大值。 ```python -# optimal solution (for the sake of completeness) +# 最优解(在此为完整性提供) def max_key_optimal(x): return max(x, key=x.get) ``` @@ -510,9 +508,9 @@ def max_key_optimal(x): 'd' ``` -You can read more about this `key` parameter [here](https://docs.python.org/3/howto/sorting.html#key-functions). +你可以在[这里](https://docs.python.org/3/howto/sorting.html#key-functions)阅读 `key` 参数。 -Next, generalize your solution for a dictionary whose values are not necessarily unique. Return a tuple of the keys that map to that max value. +接下来,让你的解可以处理词典有重复值的情况。返回成员为对应最大值的键的元组。 ```python def get_maxes(dictionary): diff --git a/Python/Module2_EssentialsOfPython/ForLoops.md b/Python/Module2_EssentialsOfPython/ForLoops.md index 4b37e61..52e5cfc 100644 --- a/Python/Module2_EssentialsOfPython/ForLoops.md +++ b/Python/Module2_EssentialsOfPython/ForLoops.md @@ -4,164 +4,164 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Contorl flow with for-loops and while-loops, Difficulty: Easy, Category: Section :keywords: for-loop, while-loop, break, control flow, basic programming -``` + -# For-Loops and While-Loops -In this section, we will introduce the essential "for-loop" control flow paradigm along with the formal definition of an "iterable". The utility of these items cannot be understated. Moving forward, you will likely find use for these concepts in nearly every piece of Python code that you write! +# For循环和While循环 +在本节中我们将会介绍“for循环”控制流以及“可迭代物”(iterable)的正式定义。这些功能极其强大强大。在未来,你会在你编写的Python代码中随处见到这些概念!
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-## For-Loops -A "for-loop" allows you to iterate over a collection of items, and execute a block of code once for each iteration. For example, the following code will sum up all the positive numbers in a tuple: +## For循环 +一个“for循环”(for-loop)允许我们迭代某个集合中的成员,并为每一次成员执行同一块代码。比如说,以下的代码会求元组中所有正数的和: ```python total = 0 for num in (-22.0, 3.5, 8.1, -10, 0.5): if num > 0: total = total + num ``` -The general syntax for a "for-loop" is: +“for循环”的语法为: ``` for in : - block of code + 一区块代码 ``` -Where `` is any valid variable-identifier and `` is any **iterable**. We will discuss iterables more formally in the next section; suffice it to know that every sequence-type object is an iterable. The `for`statement must end in a colon character, and the body the for-loop is [whitespace-delimited](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope). +`` 指代任何合法的变量身份(variable-identifier),`` 则是任何**可迭代物**。我们会在下一节中更正式地讨论迭代物;现在你只需要知道任何序列都是可迭代物这一事实就行了。`for` 语句必须由一个冒号结尾,且for循环的主体必须由[空格限定](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python使用空格来限定区域)。 -The for-loop behaves as follows: +for循环的行为如下: -- Request the next member of the iterable. -- If the iterable is empty, exit the for-loop without running its body. -- If the iterable did produce a member, assign that member to `` (if `` was not previously defined, it becomes defined). -- Execute the enclosed body of code. -- Go back to the first step. +- 试图获取可迭代物的下一个成员。 +- 如果可迭代物是空的,退出for循环且不运行其主体代码。 +- 如果可迭代物提供了一个成员,为 `` 赋值为该成员(如果 `` 在之前并没有被定义,它将会在这里被定义)。 +- 执行循环的主体代码。 +- 返回第一步。 -To be concrete, let's consider the example: +让我们来看一看一个例子吧: ```python -# demonstrating a basic for-loop +# 演示基本的for循环 total = 0 for item in [1, 3, 5]: total = total + item -print(total) # `total` has the value 1 + 3 + 5 = 9 -# `item` is still defined here, and holds the value 5 +print(total) # `total` 的值为 1 + 3 + 5 = 9 +# `item` 在这里依然被定义,且其值为5 ``` -This code will perform the following steps: +此代码会执行以下的步骤: -1. Define the variable `total`, and assign it the value `0` -2. Iterate on the list, producing value `1`, define the variable `item` and assign it the value `1` -3. Assign `total` the value `0 + 1` -4. Iterate on the list, producing the value `3` and assigning it to `item` -5. Assign `total` the value `1 + 3` -6. Iterate on the list, producing the value `5` and assigning it to `item` -7. Assign `total` the value `4 + 5` -8. Iterate on the list. Having reached its end, a `StopIteration` signal it raised by the list, and the for-loop sequence is exited. -9. Print the value of `total` (9) +1. 定义变量 `total`,并为其赋值 `0` +2. 迭代此列表,得出值 `1`,定义变量 `item` 并为其赋值 `1` +3. 为 `total` 赋值 `0 + 1` +4. 迭代此列表,得出值 `3` 并为 `item` 赋值该数字 +5. 为 `total` 赋值 `1 + 3` +6. 迭代此列表,得出值 `5` 并为 `item` 赋值该数字 +7. 为 `total` 赋值 `4 + 5` +8. 迭代此列表。因为现在已经在列表结尾,列表将提供一个 `StopIteration` 信号,并导致for循环退出 +9. 打印 `total` 的值(9) -#### Potential Pitfall -Note that the variable `item` will persist after the for-loop block is exited. It will reference the last value from the for-loop iteration (in this case `item` has the value 5). That being said, *you should not write code that depends on the iterate-variable, outside of the context of the for-loop*. In the case that you try to loop over an *empty* iterable, the iterate-variable is never defined: +#### 可能的错误 +注意迭代变量 `item` 在for循环退出之后依然存在。它会引用for循环迭代的最后一个值(在这个例子中 `item` 的值为5)。就算如此,*你不应该在for循环外面使用迭代变量*。因为如果你循环一个*空*的可迭代物,迭代变量不会被定义: ```python -for x in []: # the iterable is empty - the iterate-variable `x` will not be defined - print("Hello?") # this code is never executed -print(x) # raises an error because `x` was never defined +for x in []: # 可迭代物是空的——迭代变量 `x` 将不会被定义 + print("Hello?") # 此代码不会被执行 +print(x) # 程序报错,因为 `x` 没有被定义 ``` -Because we are attempting to iterate over an empty list, `StopIteration` is raised immediately - before the variable `x` is even defined. Thus the code enclosed within the for-loop is never reached, and the subsequent `print(x)` statement will raise a `NameError`, because `x` was never defined! +当我们试图迭代一个空列表时,程序会在变量 `x` 被定义之前立刻收到 `StopIteration` 信号。for循环中的代码块一次都没有被执行。因为 `x` 没有被定义,之后的 `print(x)` 语句会导致 `NameError`!
-**Reading Comprehension: A basic for-loop** +**阅读理解:简单for循环** -Using a for-loop and an if-statement, print each letter in the string `"abcdefghij"`, if that letter is a vowel. +使用一个for循环和一个if语句,打印字符串 `"abcdefghij"` 中的每一个元音(vowel,也就是aeiou这几个字母)。
-## While-Loops -A "while-loop" allows you to repeat a block of code until a condition is no longer true: +## While循环 +一个“while循环”(while-loop)允许你重复一区块代码,直到某个条件不再满足: ``` while : - block of code + 代码块 ``` -Where `` is an expression that returns `True` or `False`, or is any object on which `bool` can be called. The "body" of the while-loop is the code indented beneath the while-loop statement. +`` 是一个会返回 `True` 或 `False` 的表达式,或任何可以转化为 `bool` 的对象。while循环的“主体”则是在循环语句下方缩进的代码。 -The while-loop behaves as follows: +while循环的行为如下: -- Call `bool()` and execute the indented block of code if `True` is returned. Otherwise, "exit" the while-loop, skipping past the indented code. -- If the indented block code is executed, go back to the first step. +- 执行 `bool()` 并在表达式返回 `True` 时执行下方缩进的代码区块。不然,“退出”while循环并跳过其缩进代码。 +- 如果缩进的代码块被执行了,回到第一步。 -To be concrete, let's consider the example: +让我们观察一个例子: ```python -# demonstrating a basic while-loop +# 演示基本的while循环 total = 0 while total < 2: - total += 1 # equivalent to: `total = total + 1` + total += 1 # 和 `total = total + 1` 等值 -print(total) # `total` has the value 2 +print(total) # `total` 现在的值为 2 ``` -This code will perform the following steps: +此代码会执行以下步骤: -1. Define the variable `total`, and assign it the value `0` -2. Evaluate `0 < 2`, which returns `True`: enter the enclosed code-block -3. Execute the code block: assign `total` the value `0 + 1` -4. Evaluate `1 < 2`, which returns `True`: enter the enclosed code-block -5. Execute the code block: assign `total` the value `1 + 1` -6. Evaluate `2 < 2`, which returns `False`: *skip* the enclosed code-block -7. Print the value of `total` (2) +1. 定义变量 `total`,并为其赋值 `0` +2. 运算 `0 < 2`,其返回 `True`:进入循环主体的代码块 +3. 执行代码块:为 `total` 赋值 `0 + 1` +4. 运算 `1 < 2`,其返回 `True`:进入循环主体的代码块 +5. 执行代码块:为 `total` 赋值 `1 + 1` +6. 运算 `2 < 2`,其返回 `False`:*跳过*循环主体的代码块 +7. 打印 `total` 的值(2) -Note that if we started off with `total = 3`, the condition-expression `3 < 2` would evaluate to `False` outright, and the indented body of code would never be reached. +注意,如果我们一开始定义 `total = 3`,那条件表达式 `3 < 2` 会直接返回 `False`,且缩进的代码块将一次都不会执行。
-**Warning!** +**警告!** -It is possible to write a while-loop such that its conditional statement is always True, in which case your code will run ceaselessly! If this ever happens to you in a Jupyter notebook, either interrupt or restart your kernel. +你可能(一不小心)编写了条件语句永远为真的while循环。这会导致你的代码无限运行!如果这在Jupyter记事本中意外发生,打断或重启你的壳(kernel)。
-**Reading Comprehension: A basic while-loop** +**阅读理解:简单while循环** -Given a list of nonzero, positive numbers, `x`, append the sum of that list to the end of it. Do this until the last value in `x` is at least 100. Use a while-loop. +设一列表 `x`,其成员皆为的非零正数。在列表的结尾附加列表所有值的和。重复进行这一步,直到 `x` 的最后一个成员的值至少是100。使用一个while循环。 -If you start with `x = [1]`, then by the end of your while-loop `x` should be `[1, 1, 2, 4, 8, 16, 32, 64, 128]`. +如果你定义 `x = [1]`,那在你的while循环结束后 `x` 应该是 `[1, 1, 2, 4, 8, 16, 32, 64, 128]`。
-## `break`, `continue`, & `else` clauses on loops -The `continue` and `break` statements can be used within the bodies of both for-loops and while-loops. They provide added means for "short-circuiting" or prematurely exiting a given loop, respectively. +## 循环中的 `break`,`continue`,和 `else` 句段 +你可以在for循环和while循环的主体中使用 `continue` 和 `break` 语句。它们分别提供一些额外的“短路”和提前退出循环的方式。 -Encountering `break` within a given loop causes that loop to be exited immediately: +在循环中遇到 `break` 会导致程序立刻退出循环: -```ipython -# breaking out of a loop early +```python +# 提前退出循环 >>> for item in [1, 2, 3, 4, 5]: ... if item == 3: ... print(item, " ...break!") @@ -174,10 +174,10 @@ Encountering `break` within a given loop causes that loop to be exited immediate 3 ...break! ``` -An `else` clause can be added to the end of any loop. The body of this else-statement will be executed *only if the loop was not exited via a `break` statement*. +你可以在任何循环结尾添加一个 `else` 句段。此else语句的主体*只有在循环自然退出(没有被 `break` 语句打断)后才会执行*。 -```ipython -# including an else-clause at the end of the loop +```python +# 在循环结尾添加一个else句段 >>> for item in [2, 4, 6]: ... if item == 3: ... print(item, " ...break!") @@ -193,9 +193,9 @@ An `else` clause can be added to the end of any loop. The body of this else-stat if you are reading this, then the loop completed without a 'break' ``` -The `continue` statement, when encountered within a loop, causes the loop-statement to be revisited immediately. +在循环中遇到 `continue` 语句会导致程序立刻回到检查条件语句这一步。 ```python -# demonstrating a `continue` statement in a loop +# 演示循环中的 `continue` 语句 >>> x = 1 >>> while x < 4: ... print("x = ", x, ">> enter loop-body <<") @@ -218,25 +218,25 @@ x = 3 >> enter loop-body <<
-**Reading Comprehension: conducting flow in a loop** +**阅读理解:控制循环中的流** -Loop over a list of integers repeatedly, summing up all of its even values, and adding the content to a total. Repeat this process until the the total exceeds 100, or if you have looped over the list more than 50 times. Print the total only if it exceeds 100. +重复循环一个整数列表,求其中偶数的和并将此和加到一个总值中。重复此过程,直到总值超过100,或已经循环这个列表超过50次。在总值大于等于100时打印它。
-## Links to Official Documentation +## 官方说明文档链接 -- ['for' statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) -- ['while' statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement) -- ['break', 'continue', and 'else' clauses](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) -- ['pass' statment](https://docs.python.org/3/tutorial/controlflow.html#pass-statements) +- [“for”语句](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) +- [“while”语句](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement) +- [“break”,“continue”,和“else”句段](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) +- [“pass”语句](https://docs.python.org/3/tutorial/controlflow.html#pass-statements) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**A basic for-loop: Solution** +**简单for循环:解** ```python for letter in "abcdefghij": if letter in "aeiou": @@ -246,7 +246,7 @@ for letter in "abcdefghij": -**A basic while-loop: Solution** +**简单while循环:解** ```python while x[-1] < 100: x.append(sum(x)) @@ -254,7 +254,7 @@ while x[-1] < 100: -**Conducting flow in a loop: Solution** +**控制循环中的流:解** ```python x = [3, 4, 1, 2, 8, 10, -3, 0] @@ -263,16 +263,16 @@ total = 0 while total < 100: for item in x: - # return to for-loop if - # `item` is odd-valued + # 当 `item` 是奇数时立刻跳到 + # 下一轮for循环 if item % 2 == 1: continue else: total += item num_loop += 1 - - # break from while-loop if - # more than 50 items tallied + + # 只有在循环了50次之后才 + # 打断while循环中 if 50 < num_loop: break else: diff --git a/Python/Module2_EssentialsOfPython/Functions.md b/Python/Module2_EssentialsOfPython/Functions.md index a2d8c6c..333b0a1 100644 --- a/Python/Module2_EssentialsOfPython/Functions.md +++ b/Python/Module2_EssentialsOfPython/Functions.md @@ -4,51 +4,51 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Functions and Function Signatures, Difficulty: Medium, Category: Section :keywords: functions, *args, **kwargs, signature, default parameter, docstring, return, vowel count, syntax, basics -``` + -# Basics of Functions +# 函数基础
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +在本资源各处会有一些阅读理解练习。这些题目旨在帮助读者活学活用文中的知识点。练习题的答案可以在本页底部找到。
-Defining a function allows you to encapsulate a segment of code, specifying the information that enters and leaves the code. You can make use of this "code-capsule" repeatedly and in many different contexts. For example, suppose you want to count how many vowels are in a string. The following defines a function that accomplishes this: +定义函数允许我们包装代码片段并描述进入和离开其中的信息。你可以在各种情况下重复使用这个“代码胶囊”。比如说,假设你想要数一个字符串中有多少元音,你可以定义以下的函数来达到该目的: ```python def count_vowels(in_string): - """ Returns the number of vowels contained in `in_string`""" + """ 返回 `in_string` 中有多少元音 """ num_vowels = 0 vowels = "aeiouAEIOU" for char in in_string: if char in vowels: - num_vowels += 1 # equivalent to num_vowels = num_vowels + 1 + num_vowels += 1 # 等值于 num_vowels = num_vowels + 1 return num_vowels ``` -Executing this code will define the *function* `count_vowels`. This function expects to be passed one object, represented by `in_string`, as an *input argument*, and it will *return* the number of vowels stored in that object. Invoking `count_vowels`, passing it an input object, is referred to as *calling* the function: +执行此代码会定义*函数* `count_vowels`。这个函数期待一个对象作为*输入参数*(input argument),由 `in_string` 代名,并会*返回*(return)该对象中元音的数量。使用 `count_vowels` 并向其输入一个对象的过程叫做*调用*(call)该函数: ```python >>> count_vowels("Hi my name is Ryan") 5 ``` -The great thing about this is that it can be used over and over! +最棒的一点在于你可以重复使用这个函数! ```python >>> count_vowels("Apple") @@ -58,62 +58,61 @@ The great thing about this is that it can be used over and over! 4 ``` -In this section, we will learn about the syntax for defining and calling functions in Python +在本节中,我们将会了解定义和调用Python函数的语法。
-**Definition**: +**定义**: -A Python **function** is an object that encapsulates code. *Calling* the function will execute the encapsulated code and *return* an object. A function can be defined so that it accepts *arguments*, which are objects that are to be passed to the encapsulated code. +Python**函数**(function)是一个包装代码的对象。*调用*(call)函数将会执行包装的代码并*返回*(return)一个对象。你可以定义函数使其接受*参数*(argument),也就是输入进包装代码的对象。
- -## The `def` Statement -Similar to `if`, `else`, and `for`, the `def` statement is reserved by the Python language to signify the definition of functions (and a few other things that we'll cover later). The following is the general syntax for defining a Python function: + +## `def` 语句 +类似于 `if`,`else`,和 `for`,Python保留了 `def` 语句来表达函数(以及我们会在之后讨论的其它几个构造体)的定义。以下是Python函数定义的一般形式: ``` def (): - """ documentation string """ + """ 说明字符串 """ return ``` -- `` can be any valid variable name, and *must* be followed by parentheses and then a colon. -- `` specifies the input arguments to the function, and may be left blank if the function does not accept any arguments (the parentheses must still be included, but will not encapsulate anything). -- The documentation string (commonly referred to as a "docstring") may span multiple lines, and should indicate what the function's purpose is. It is optional. -- `` can consist of general Python code, and is demarcated by being indented relative to the `def` statement. -- `return` if reached by the encapsulated code, triggers the function to return the specified object and end its own execution immediately. - -The `return` statement is also reserved by Python. It denotes the end of a function; if reached, a `return` statement immediately concludes the execution of the function and returns the specified object. +- `` 是任何合法的变量名,在这之后*必须*跟随一对括号和一个冒号。 +- `` 描述函数的输入参数。如果函数不接受任何变量,你可以留白这一部分(你仍然需要提供括号,但是仅仅括号并不会包装任何参数)。 +- 说明字符串(documentation string)(一般叫做“docstring”)可以长达多行并解释函数的目的。它是可选的。 +- `` 包含正常的Python代码,其由相对于 `def` 语句的缩进限定。 +- `return` 当函数中包装的代码遇到这个标示后,函数会返回标示后跟随的对象并立刻终止函数的执行。 -Note that, like an if-statement and a for-loop, the `def` statment must end in a colon and the body of the function is [delimited by whitespace](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope): - +Python同样保留了 `return` 语句来表达函数的终止;如果遇到了 `return`,那程序将立即终止函数的执行并返回 `return` 右边的对象。 + +请注意,与if语句和for循环一样,`def` 语句必须由冒号结尾,且函数的主体代码必须[由空格限定](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python使用空格来限定区域): ```python -# wrong indentation +# 错误的缩进 def bad_func1(): x = 1 return x + 2 ``` *** ```python -# wrong indentation +# 错误的缩进 def bad_func2(): x = 1 return x + 2 ``` *** ```python -# missing colon +# 漏了冒号 def bad_func3() x = 1 return x + 2 ``` *** ```python -# missing parenthesis +# 漏了括号 def bad_func4: x = 1 return x + 2 @@ -121,7 +120,7 @@ def bad_func4: *** ```python -# this is ok +# 这个没问题 def ok_func(): x = 1 return x + 2 @@ -130,37 +129,37 @@ def ok_func():
-**Reading Comprehension: Writing a Basic Function** +**阅读理解:编写简单函数** -Write a function named `count_even`. It should accept one input argument, named `numbers`, which will be an iterable containing integers. Have the function return the number of even-valued integers contained in the list. Include a reasonable docstring. +编写一个名为 `count_even` 的函数。它应该接受一个名为 `numbers` 的整数可迭代物作为参数。该函数应该返回列表中偶数的数量。注意包含一个合理的docstring。
-## The `return` Statement -In general, any Python object can follow a function's `return` statement. Furthermore, an **empty** `return` statement can be specified, or the **return** statement of a function can be omitted altogether. In both of these cases, *the function will return the `None` object*. +## `return` 语句 +一般来讲,`return` 语句可以返回任何Python对象。同时,你可以使用一个**空的** `return` 语句或在函数中完全不使用**返回**(return)语句。在这两种情况下,*函数都会返回 `None` 对象*。 ```python -# this function returns `None` -# an "empty" return statement +# 本函数返回 `None` +# 一个“空”的返回语句 def f(): x = 1 return ``` ```python -# this function returns `None` -# return statement is omitted +# 本函数返回 `None` +# 完全没有用返回语句 def f(): x = 1 ``` -All Python functions return *something*. Even the built-in `print` function returns `None` after it prints to standard-output! +所有Python函数都会返回*某个对象*。就算是内置的 `print` 函数在打印后也会返回 `None`! ```python -# the `print` function returns `None` +# `print` 函数返回 `None` >>> x = print("hi") hi @@ -169,28 +168,28 @@ True ```
-**Warning!** +**警告**! -Take care to not *mistakenly* omit a return statement or leave it blank. You will still be able to call your function, but it will return `None` no matter what! +请注意不要*错误地*漏掉或使用空的返回语句。你将依然能够调用你的函数,但是它在任何情况下都会返回 `None`!
-A function also need not have any additional code beyond its return statement. For example, we can make use of `sum` and a generator comprehension (see the previous section of this module) to shorten our `count_vowels` function: +函数并不一定要有除了返回语句之外的代码。比如说,我们可以使用 `sum` 和生成器理解(见本模组前一节)来简化我们的 `count_vowels` 函数: ```python -# the returned object of a function can be specified straight-away +# 你可以直接描述函数返回的对象 def count_vowels(in_string): - """ Returns the number of vowels contained in `in_string`""" + """ 返回 `in_string` 中元音的数量 """ return sum(1 for char in in_string if char in "aeiouAEIOU") ``` -### Multiple `return` Statements -You can specify more than one `return` statement within a function. This can be useful for handling edge-cases or optimizations in your code. Suppose you want your function to compute $e^{x}$, using a [Taylor series](https://en.wikipedia.org/wiki/Taylor_series#Exponential_function) approximation. The function should immediately return `1.0` in the case that $x = 0$: +### 多个 `return` 语句 +你可以在一个函数内使用不止一个 `return` 语句。在处理边缘情况或优化代码时这可能会有用。假设你想要你的函数通过[泰勒级数](https://en.wikipedia.org/wiki/Taylor_series#Exponential_function)(Taylor series)来模糊计算 $e^{x}$,当 $x = 0$ 时函数应该立刻返回 `1.0`: ```python def compute_exp(x): - """ Use a Taylor Series to compute e^x """ + """ 使用泰勒级数来计算 e^x """ if x == 0: return 1.0 @@ -198,21 +197,21 @@ def compute_exp(x): return sum(x**n / factorial(n) for n in range(100)) ``` -If `x==0` is `True`, then the first `return` statement is reached. `1.0` will be returned and the function will be "exited" immediately, without ever reaching the code following it. +如果 `x==0` 为 `True`,那么程序将执行第一个 `return` 语句,返回 `1.0` 并立刻“终止”该函数,且不执行之后的代码。 -As stated above, a `return` statement will trigger a function to end its execution immediately when reached, even when subsequent code follows it. *It is impossible for multiple `return` statements to be visited within a single function call*. Thus if you want to return multiple items, then your function must return a single container of those items, like a list or a tuple. +如上所述,就算下方有额外的代码,`return` 语句也会导致函数立刻终止且不执行之后的代码。*在一次函数调用中,程序不可能遇到多个 `return` 语句*。因此,如果你想要返回多个对象,那么你的函数必须返回单个包含这些项目的容器,如列表会元组。 ```python -# Returning multiple items from a function -def bad_f(x): - """ return x**2 and x**3""" - return x**2 - # this code can never be reached! +# 函数返回多个项目 +def bad_f(x): # 译者注:函数名字大意为:不好的函数 + """ 返回 x**2 和 x**3""" + return x**2 + # 此代码永远都不会被执行! return x**3 -def good_f(x): +def good_f(x): # 译者注:函数名字大意为:好的函数 """ return x**2 and x**3""" return (x**2, x**3) ``` @@ -226,122 +225,122 @@ def good_f(x): -## Inline Functions -Functions can be defined in-line, as a single return statement: +## 单行函数 +你可以在一行内定义只有一个返回语句的函数: ```python def add_2(x): return x + 2 ``` -can be rewritten as: +可以被重写为: ```python def add_2(x): return x + 2 ``` -This should be used sparingly, for exceedingly simple functions that can be easily understood without docstrings. +尽量只在函数极其简单到不需要docstring就能理解时使用此功能。切记不要滥用。 -## Arguments -A sequence of comma-separated variable names can specified in the function signature to indicated *positional* arguments for the function. For example, the following specifies `x`, `lower`, and `upper` as input arguments to a function, `is_bounded`: +## 参数 +你可以在函数签名(function signature)部分通过一序列由逗号隔开的变量名来描述函数的*位置*参数(positional argument)。比如说,以下代码为函数 `is_bounded` 提供了 `x`,`lower`,和 `upper` 三个参数: ```python def is_bounded(x, lower, upper): return lower <= x <= upper ``` -This function can then be passed its arguments in several way: +你可以用几种不同的方法来向函数提供参数: -### Specifying Arguments by Position -The objects passed to `is_bounded` will be assigned to its input variables based on their positions. That is, `is_bounded(3, 2, 4)` will assign `x=3`, `lower=2`, and `upper=4`, in accordance with the positional ordering of the function's input arguments: +### 通过位置提供参数 +输入到 `is_bounded` 中的对象会根据它们的位置来赋值函数的输入变量。也就是说,`is_bounded(3, 2, 4)` 会赋值 `x=3`,`lower=2`,和 `upper=4`,其根据函数输入参数的位置顺序来对应: ```python -# evaluate: 2 <= 3 <= 4 -# specifying inputs based on position +# 计算:2 <= 3 <= 4 +# 通过位置来提供输入 >>> is_bounded(3, 2, 4) True ``` -Feeding a function too few or too many arguments will raise a `TypeError` +向函数输入太少或太多参数会导致 `TypeError`。 ```python -# too few inputs: raises error +# 输入太少:报错 is_bounded(3) -# too many inputs: raises error +# 输入太多:报错 is_bounded(1, 2, 3, 4) ``` -### Specifying Arguments by Name -You can provide explicit names when specifying the inputs to a function, in which case ordering does not matter. This is very nice for writing clear and flexible code: +### 通过关键词提供参数 +在顺序不重要的时候,你也可以在给函数输入参数时提供它们的关键词(也就是名字)来对应对象和参数。这会帮助你编写易读和灵活的代码: ```python -# evaluate: 2 <= 3 <= 4 -# specify inputs using explicit input names +# 计算:2 <= 3 <= 4 +# 通过参数名字来提供输入对象 >>> is_bounded(lower=2, x=3, upper=4) True ``` -You can mix-and-match positional and named input by using position-based inputs first: +你可以混合关键词参数和位置参数,但位置参数应该在前: ```python -# evaluate: 2 <= 3 <= 4 -# `x` is specified based on position -# `lower` and `upper` are specified by name +# 计算:2 <= 3 <= 4 +# `x` 是位置参数 +# `lower` 和 `upper` 关键词参数 >>> is_bounded(3, upper=4, lower=2) True ``` -Note that if you provide a named input, all the inputs following it must also be named: +请注意,如果你提供了一个关键词参数,那么它之后所有的参数都应该是关键词参数: ```python -# positional arguments cannot follow named arguments +# 你不可以在关键词参数后使用位置参数 >>> is_bounded(3, lower=2, 4) SyntaxError: positional argument follows keyword argument ``` -### Default-Valued Arguments -You can specify default values for input arguments to a function. Their default values are utilized if a user does not specify these inputs when calling the function. Recall our `count_vowels` function. Suppose we want the ability to include "y" as a vowel. We know, however, that people will typically want to exclude "y" from their vowels, so we can exclude "y" by default: +### 有默认值的参数 +你可以提供参数的默认值。如果用户在调用函数时没有提供此参数,那么函数将会使用定义的默认值。请回忆我们的 `count_vowels` 函数。假设我们想要提供将“y”算为一个元音的选择。因为我们知道人们一般不会将“y”视为元音,所以我们可以默认将“y”除外: ```python -def count_vowels(in_string, include_y=False): - """ Returns the number of vowels contained in `in_string`""" +def count_vowels(in_string, include_y=False): + """ 返回 `in_string` 中元音的数量""" vowels = "aeiouAEIOU" if include_y: - vowels += "yY" # add "y" to vowels + vowels += "yY" # 将 "y" 加到元音列表中 return sum(1 for char in in_string if char in vowels) ``` -Now, if only `in_string` is specified when calling `count_vowels`, `include_y` will be passed the value `False` by default: +现在,如果在调用 `count_vowels` 时只提供了 `in_string`,那么 `include_y` 会使用默认值 `False`: ```python -# using the default value: exclude y from vowels +# 使用默认值:不将y算为元音 >>> count_vowels("Happy") 1 ``` -This default value can be overridden: +我们可以提供默认值之外的输入: ```python -# overriding the default value: include y as a vowel +# 不使用不认值:将y算为元音 >>> count_vowels("Happy", True) 2 -# you can still specify inputs by name +# 你依然可以通过名字来描述输入参数 >>> count_vowels(include_y=True, in_string="Happy") 2 ``` -Default-valued input arguments must come after all positional input arguments in the function signature: +在函数签名中,有默认值的输入参数必须在所有位置参数之后: ```python -# this is ok +# 这没问题 def f(x, y, z, count=1, upper=2): return None ``` ```python -# this will raise a syntax error +# 这会导致语法错误 def f(x, y, count=1, upper=2, z): return None ``` @@ -349,48 +348,48 @@ def f(x, y, count=1, upper=2, z):
-**Reading Comprehension: Functions and Arguments** +**阅读理解:函数和参数** -Write a function, `max_or_min`, which accepts two positional arguments, `x` and `y` (which will hold numerical values), and a `mode` variable that has the default value `"max"`. +编写一个函数 `max_or_min`。它接受两个位置参数 `x` 和 `y`(将会被赋值为数字)以及一个 `mode` 变量,其默认值为 `"max"`。 -The function should return `min(x, y)` or `max(x, y)` according to the `mode`. Have the function return `None` if `mode` is neither `"max"` nor `"min"`. +此函数应该根据 `mode` 返回 `min(x, y)` 或 `max(x, y)`。如果 `mode` 既不是 `"max"` 也不是 `"min"` 的时候让函数返回 `None`。 -Include a descriptive doc-string. +包含一个描述性的docstring。
-### Accommodating an Arbitrary Number of Positional Arguments -Python provides us with a syntax for defining a function, which can be called with an arbitrary number of positional arguments. This is signaled by the syntax `def f(*)`. +### 支持任意多的位置参数 +Python提供了定义可以接受任意多位置参数的函数的语法。使用 `def f(*)` 语法来定义这类输入。 ```python -# The * symbol indicates that an arbitrary number of -# arguments can be passed to `args`, when calling `f`. +# * 符号表明调用 `f` 时可以向 `args` +# 输入任意多的参数。 def f(*args): - # All arguments passed to `f` will be "packed" into a - # tuple that is assigned to the variable `args`. - # `f()` will assign `args = tuple()` - # `f(x, y, ...)` will assign `args = (x, y, ...)` + # 所有向 `f` 输入的参数都会被“打包”成一个元组 + # 并赋值给变量 `args`。 + # `f()` 会赋值 `args = tuple()` + # `f(x, y, ...)` 会赋值 `args = (x, y, ...)` return args ``` -Because Python cannot foresee how many arguments will be passed to `f`, all of the objects that are passed to it will be *packed into a tuple*, which is then assigned to the variable `args`: +因为Python不能提前知道 `f` 会收到多少个参数,因此它所有的输入参数都会被*打包成一个元组*并赋值给变量 `args`: ```python -# pass zero arguments to `f` ->>> f() +# 向 `f` 输入0个参数 +>>> f() () -# pass one argument to `f` ->>> f(1) +# 向 `f` 输入1个参数 +>>> f(1) (1,) -# pass three arguments to `f` +# 向 `f` 输入3个参数 >>> f((0, 1), True, "cow") ((0, 1), True, "cow") ``` -This syntax can be combined with positional arguments and default arguments. Any variables specified after a packed variable *must be called by name*: +你可以将此语法与位置参数和默认参数混合使用。任何在被打包的变量后的变量*必须提供参数名*: ```python def f(x, *seq, y): print("x is: ", x) @@ -399,40 +398,39 @@ def f(x, *seq, y): return None ``` ```python ->>> f(1, 2, 3, 4, y=5) # `y` must be specified by name +>>> f(1, 2, 3, 4, y=5) # 必须提供 `y` 的名字 ``` ``` -x is: 1 -seq is: (2, 3, 4) -y is: 5 +x 是: 1 +seq 是: (2, 3, 4) +y 是: 5 ``` ```python ->>> f("cat", y="dog") # no additional positional arguments are passed +>>> f("cat", y="dog") # 没有输入任何额外的位置参数 ``` ``` -x is: "cat" -seq is: () -y is: "dog" +x 是: "cat" +seq 是: () +y 是: "dog" ```
-**Reading Comprehension: Arbitrary Arguments** +**阅读理解:任意多的参数** -Write a function named `mean`, which accepts and arbitrary number of numerical arguments, and computes the mean of all of the values passed to the function. Thus `mean(1, 2, 3)` should return $\frac{1 + 2 + 3}{3} = 2.0$ +编写一个名为 `mean` 的函数,其接受任意多的数字参数并计算所有数字的平均值。如,`mean(1, 2, 3)` 应返回 $\frac{1 + 2 + 3}{3} = 2.0$ -This function should return `0.` if no arguments are passed to it. Be sure to test your function, and include a docstring. +如果没有收到任何输入,函数应返回 `0.`。记得测试你的函数并编写一个docstring。
-We see that `*` indicates the *packing of an arbitrary number of arguments into a tuple*, when used in the signature of a function definition. Simultaneously, `*` signals the *unpacking of an iterable* to pass each of its members as a positional argument to a function, when used in the context of calling a function: +如我们所见,在函数定义的签名中使用 `*` 意味着*将任意多的参数打包成一个元组*。同时,在调用函数时 `*` 也意味着*解包可迭代物*并将其作为位置参数输入到函数中: ```python -# Using `*` when calling a function, to unpack an -# iterable. Passing its members as distinct arguments -# to the function +# 在调用函数时使用 `*` 来解包可迭代物,并将其 +# 成员作为位置参数输入到函数中 def f(x, y, z): return x + y + z @@ -440,20 +438,17 @@ def f(x, y, z): >>> f(1, 2, 3) 6 -# `*` means: unpack the contents of [1, 2, 3] -# passing each item as x, y, and z, -# respectively ->>> f(*[1, 2, 3]) # equivalent to: f(1, 2, 3) +# `*` 意味着:解包 `[1, 2, 3]` 的内容并将每个 +# 物件分别输入为x,y,和z +>>> f(*[1, 2, 3]) # 等值于:f(1, 2, 3) 6 ``` -In the following example, we use `*` to: +在以下范例中,我们使用 `*` 来: - 1. Define a function to accept an arbitrary - number of arguments, which get packed into a tuple. - 2. Call the function, passing it an arbitrary - number of arguments, by unpacking an iterable. + 1. 定义一个接受任意多参数并将其打包为元组的函数 + 2. 通过解包可迭代物来调用函数并输入任意多的参数 ```python @@ -466,66 +461,68 @@ def number_of_args(*args): >>> some_list = [1, 2, 3, 4, 5] -# passing the list itself as the sole argument +# 将列表本身作为唯一的参数输入 >>> number_of_args(some_list) 1 -# unpacking the 5 members of the list, -# passing each one as an argument to the function +# 将列表的5个成员解包并作为多个参数输入进函数 >>> number_of_args(*some_list) 5 ``` -### Accommodating an Arbitrary Number of Keyword Arguments -We can also define a function that is able to accept an arbitrary number of *keyword* arguments, using the syntax: `def f(**)` +### 支持任意多的关键词参数 +我们可以使用 `def f(**)` 语法来定义一个接受任意多的*关键词*(keyword)参数的函数。 -Note that a single asterisk, `*`, was used to denote an arbitrary number of *positional* arguments, whereas `**` signals the acceptance of an arbitrary number of *keyword* arguments. +注意单个星号 `*` 用来代表任意多的*位置*参数,而 `**` 代表着任意多的*关键词*参数。 ```python -# The ** symbol indicates that an arbitrary number of -# keyword arguments can be passed to `args`, when calling `f`. +# ** 符号意味着在调用 `f` 时可以向 `args` 输入 +# 任意多的关键词参数。 def f(**args): - # All keyword arguments passed to `f` will be "packed" into a - # dictionary that is assigned to the variable `args`. - # `f()` will assign `args = {}` (an empty dictionary) - # `f(x=1, y=2, ...)` will assign `args = {"x":1, "y":2, ...}` + # 所有输入到 `f` 的关键词参数都会被“打包”成一个词典 + # 并赋值到变量 `args` 中 + # `f()` 会赋值 `args = {}`(一个空词典) + # `f(x=1, y=2, ...)` 会赋值 `args = {"x":1, "y":2, ...}` return args ``` -Because Python cannot foresee how many arguments will be passed to `f`, all of the keyword arguments that are passed to it will be packed into a *dictionary*, where a given keyword is set as a key (cast as a string) that maps to the corresponding value. This dictionary is then assigned to the variable `args`. Dictionaries will be discussed in detail in a [later section](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html). +因为Python无法预先知道 `f` 会收到多少个关键词参数,所以所有收到的关键词参数都会被打包成一个*词典*(dictionary)。词典允许你通过关键词(将其转化成字符串)查询并设置关键词对应的值。这个词典被赋值到变量 `args` 上。我们会在[后面一节](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html)专门讨论词典。 ```python ->>> f() # pass zero arguments to `f` +>>> f() # 向 `f` 输入0个参数 {} ->>> f(x=1) # pass one argument to `f` +>>> f(x=1) # 向 `f` 输入1个参数 {'x': 1} ->>> f(x=(0, 1), val=True, moo="cow") # pass three arguments to `f` +>>> f(x=(0, 1), val=True, moo="cow") # 向 `f` 输入3个参数 {'moo': 'cow', 'val': True, 'x': (0, 1)} ``` -This syntax can be combined with positional arguments and default arguments. No additional arguments may come after a `**` entry in a function-definition signature: +这一语法可以和位置参数和默认参数混合使用。在函数定义签名中,`**` 后不能有任何额外的参数: ```python def f(x, y=2, **kwargs): - print("x is: ", x) - print("y is: ", y) - print("kwargs is: ", kwargs) + print("x 是:", x) + print("y 是:", y) + print("kwargs 是:", kwargs) return None + +# 译者注:kwargs是keyword arguments的缩写,也就是关键词参数。 +# 译者注:此命名方式是传统,所以请尽量遵循 ``` ```python -# passing arbitrary keyword arguments to `f` +# 向 `f` 输入任意的关键词参数 >>> f(1, y=9, z=3, k="hi") ``` ``` -x is: 1 -y is: 9 -kwargs is: {'z': 3, 'k': 'hi'} +x 是: 1 +y 是: 9 +kwargs 是: {'z': 3, 'k': 'hi'} ``` ```python -# no additional keyword arguments are passed +# 没有输入任何额外的关键词参数 >>> f("cat", y="dog") ``` ``` @@ -534,13 +531,13 @@ y is: dog kwargs is: {} ``` -The following function accepts an arbitrary number of positional arguments *and* an arbitrary number of keyword arguments: +以下函数接受任意多的位置参数*和*任意多的关键词参数: ```python -# accepting arbitrary positional and keyword arguments +# 接受任意多的位置和关键词参数 def f(*x, **y): - # all positional arguments get packed into the tuple `x` - # all keyword arguments get packed into the dictionary `y` + # 所有位置参数都打包成元组 `x` + # 所有关键词参数都打包成词典 `y` print(x) print(y) return None @@ -554,12 +551,11 @@ def f(*x, **y): -We see that `**` indicates the *packing of an arbitrary number of keyword arguments into a dictionary*, when used in the signature of a function definition. Simultaneously, `**` signals the *unpacking of a dictionary* to pass each of its key-value pairs as a keyword argument to a function, when used in the context of calling a function: +如上所见,在函数定义的签名中 `**` 意味着*将任意多的关键词参数打包成一个词典*。同时,在调用函数时 `**` 意味着*解包词典*并将其的键值对(key-value pair)作为函数关键词参数输入: ```python -# Using `**` when calling a function, to unpack a -# dictionary, passing its members as keyword arguments -# to the function +# 在调用函数时使用 `**` 来解包词典并将其成员作为 +# 关键词参数输入到函数中 def f(x, y, z): return 0*x + 1*y + 2*z @@ -567,17 +563,15 @@ def f(x, y, z): 21 >>> args = {"x": 9, "y": 1, "z": 10} ->>> f(**args) # equivalent to: f(x=9, y=1, z=10) +>>> f(**args) # 等值于:f(x=9, y=1, z=10) 21 ``` -In the following example, we use `**` to: +在以下范例中,我们用 `**` 来: - 1. Define a function to accept an arbitrary - number of keyword arguments, which get packed into a dictionary. - 2. Call the function, passing it an arbitrary - number of keyword arguments, by unpacking a dictionary. + 1. 定义一个接受任意多关键词参数的函数并将其打包成词典。 + 2. 调用函数并通过解包词典向其输入任意多的关键词参数。 ```python @@ -590,105 +584,102 @@ def print_kwargs(**args): >>> some_dict = {"hi":1, "bye":2} -# unpacking the key-value pairs of the dictionary -# as keyword arguments and values, to the function +# 解包词典的键值对并将其作为关键词参数输入到函数中 >>> print_kwargs(a=2, umbrella=True, **some_dict) {'a': 2, 'umbrella': True, 'hi': 1, 'bye': 2} ``` -## Functions are Objects -Once defined, a function behaves like any other Python object, like a list or string or integer. You can assign a variable to a function-object: +## 函数也是对象 +在定义之后,函数和任何其它Python对象,如列表或字符串或整数,的行为差不多。你可以将函数赋值到变量上: ```python ->>> var = count_vowels # `var` now references the function `count_vowels` ->>> var("Hello") # you can now "call" `var` +>>> var = count_vowels # `var` 现在引用函数 `count_vowels` +>>> var("Hello") # 你现在可以“调用” `var` 2 ``` -You can store functions in a list: +你可以将函数存储到一个列表中: ```python my_list = [count_vowels, print] for func in my_list: func("hello") -# iteration 0: calls `count_vowels("hello")` -# iteration 1: calls `print("hello")` +# 迭代0:调用 `count_vowels("hello")` +# 迭代1:调用 `print("hello")` ``` -You can also call functions anywhere, and their return-value will be returned in-place: +你也可以在代码任何地方调用函数,且它的返回值会在原地返回: ```python if count_vowels("pillow") > 1: print("that's a lot of vowels!") ``` -And, of course, this works within comprehension expressions as well: +当然,这在列表理解表达式中也成立: ```python >>> sum(count_vowels(word, include_y=True) for word in ["hi", "bye", "guy", "sigh"]) 6 ``` -"Printing" a function isn't very revealing. It simply tells you the memory address where the function-object is stored: +“打印”一个函数并不会揭露些什么。这仅仅打印此函数对象在内存中的地址: ```python >>> print(count_vowels) ``` -## Links to Official Documentation +## 官方说明文档链接 -- [Definition of 'function'](https://docs.python.org/3/library/stdtypes.html#functions) -- [Defining functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) -- [Default argument values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values) -- [Keyword arguments](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments) -- [Specifying arbitrary arguments](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists) -- [Unpacking arguments](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) -- [Documentation strings](https://docs.python.org/3/tutorial/controlflow.html#documentation-strings) -- [Function annotations](https://docs.python.org/3/tutorial/controlflow.html#function-annotations) +- [“函数”的定义](https://docs.python.org/3/library/stdtypes.html#functions) +- [定义函数](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) +- [定义参数值](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values) +- [关键词参数](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments) +- [提供任意多的参数](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists) +- [解包参数](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) +- [docstring](https://docs.python.org/3/tutorial/controlflow.html#documentation-strings) +- [函数注解](https://docs.python.org/3/tutorial/controlflow.html#function-annotations) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**Writing a Basic Function: Solution** +**编写简单函数:解** ```python def count_even(numbers): - """ Counts the number of even integers in an iterable""" + """ 返回可迭代物中偶数的数量 """ total_even = 0 for num in numbers: if num % 2 == 0: total += 1 return total ``` -or, using a generator comprehension: +或通过使用生成器理解: ```python def count_even(numbers): - """ Counts the number of even integers in an iterable""" + """ 返回可迭代物中偶数的数量 """ return sum(1 for num in numbers if num % 2 == 0) ``` -**Functions and Arguments: Solution** +**函数和参数:解** ```python def max_or_min(x, y, mode="max"): - """ Return either `max(x,y)` or `min(x,y)`, - according to the `mode` argument. - + """ 根据 `mode` 参数返回 `max(x,y)` 或 `min(x,y)`。 + Parameters ---------- x : Number - + y : Number - + mode : str - Either 'max' or 'min' - + 'max' 或 'min' + Returns ------- - The max or min of the two values. `None` is - returned if an invalid mode was specified.""" + 两值的最大或最小值。如果mode不合法那么会返回 `None`。""" if mode == "max": return max(x, y) elif mode == "min": @@ -697,9 +688,9 @@ def max_or_min(x, y, mode="max"): return None ``` -Note that you can actually have your function raise an "exception" (an error) in the case that `mode` wasn't passed a proper value. In fact, that is likely the more appropriate behavior for this function. +请注意你其实可以在 `mode` 输入不正确时让你的函数报错(raise an “exception”)。事实上,这才应该是这种情况下更加合理的函数行为。 -Such a solution would look like: +这种解决方案如下: ```python def max_or_min(x, y, mode="max"): if mode == "max": @@ -710,11 +701,11 @@ def max_or_min(x, y, mode="max"): raise Exception("`mode` was passed an invalid value: {}".format(mode)) ``` -**Arbitrary Arguments: Solution** +**任意多的参数:解** ```python def mean(*seq): - """ Returns the mean of the function's arguments """ + """ 返回函数参数的平均值 """ if len(seq) == 0: return 0 @@ -724,14 +715,14 @@ def mean(*seq): return total / len(seq) ``` -or, being a bit more fancy : +或者我们可以利用以下两点来做一些骚操作: -- using the fact that `bool(seq)` is `False` if `seq` is empty -- using the inline if-else syntax +- 当 `seq` 为空时 `bool(seq)` 是 `False` 的事实 +- 单行if-else语法 ```python def mean(*seq): - """ Returns the mean of the function's arguments """ + """ 返回函数参数的平均值 """ return sum(seq) / len(seq) if seq else 0 ``` diff --git a/Python/Module2_EssentialsOfPython/Generators_and_Comprehensions.md b/Python/Module2_EssentialsOfPython/Generators_and_Comprehensions.md index dc4caa4..b87f1a0 100644 --- a/Python/Module2_EssentialsOfPython/Generators_and_Comprehensions.md +++ b/Python/Module2_EssentialsOfPython/Generators_and_Comprehensions.md @@ -4,122 +4,122 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: generators comprehensions and efficiency, Difficulty: Easy, Category: Section :keywords: generator, range, list comprehension, generator comprehension, nested comprehensions, inline for-loop, filtered, iterator -``` + -# Generators & Comprehension Expressions +# 生成器和理解表达式
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +本文各处的阅读理解练习旨在帮助你练习使用文章中的知识点。练习题的答案可以在本页结尾找到。
-## Introducing Generators -Now we introduce an important type of object called a **generator**, which allows us to generate arbitrarily-many items in a series, without having to store them all in memory at once. +## 生成器简介 +现在,让我们介绍一种重要的对象,**生成器**(generator)。它允许我们生成(generate)任意长度的序列,并不需要同时在内存中存储其所有的成员。
-**Definition**: +**定义**: -A **generator** is a special kind of iterator, which stores the instructions for how to *generate* each of its members, in order, along with its current state of iterations. It generates each member, one at a time, only as it is requested via iteration. +**生成器**是一种特殊的迭代器。它存储如何顺序*生成*新成员的指示以及迭代的内态。它在收到请求后会一次一个生成其成员。
-Recall that that a list readily stores all of its members; you can access any of its contents via indexing. A generator, on the other hand, *does not store any items*. Instead, it stores the instructions for generating each of its members, and stores its iteration state; this means that the generator will know if it has generated its second member, and will thus generate its third member the next time it is iterated on. +请回忆列表同时存储其所有成员这一事实;你可以通过迭代访问其任何成员。与列表不同的是,生成器*不存储任何成员*。它存储如何生成新成员的指示以及它迭代的内态;这意味着如果生成器已经生成了第二个成员,它会知道这一点并在下次迭代时生成第三个成员。 -The whole point of this is that you can use a generator to produce a long sequence of items, without having to store them all in memory. +以上太长不读的版本就是说你可以用生成器来生成长的成员序列,而并不需要将它们全部同时储存在内存中。 -### The `range` generator -An extremely popular built-in generator is `range`, which, given the values: +### `range` 生成器 +`range` 是一个很常用的内置生成器。它接受以下输入值: -- 'start' (inclusive, default=0) -- 'stop' (exclusive) -- 'step' (default=1) +- “start”(包括数字本身,默认为0) +- “stop”(不包括数字本身) +- “step”(默认为1) -will generate the corresponding sequence of integers (from start to stop, using the step size) upon iteration. Consider the following example usages of `range`: +并以此在迭代时生成对应的整数序列(从start到stop,步距为step)。看看以下的 `range` 使用范例: ```python -# start: 2 (included) -# stop: 7 (excluded) -# step: 1 (default) +# start: 2(包含) +# stop: 7(不包含) +# step: 1(默认) for i in range(2, 7): print(i) -# prints: 2.. 3.. 4.. 5.. 6 +# 打印:2.. 3.. 4.. 5.. 6 ``` *** ```python -# start: 1 (included) -# stop: 10 (excluded) +# start: 1(包含) +# stop: 10(不包含) # step: 2 for i in range(1, 10, 2): print(i) -# prints: 1.. 3.. 5.. 7.. 9 +# 打印:1.. 3.. 5.. 7.. 9 ``` *** ```python -# A very common use case! -# start: 0 (default, included) -# stop: 5 (excluded) -# step: 1 (default) +# 一个很常见的使用范例! +# start: 0(默认,包含) +# stop: 5(不包含) +# step: 1(默认) for i in range(5): print(i) -# prints: 0.. 1.. 2.. 3.. 4 +# 打印:0.. 1.. 2.. 3.. 4 ``` -Because `range` is a generator, the command `range(5)` will simply store the instructions needed to produce the sequence of numbers 0-4, whereas the list `[0, 1, 2, 3, 4]` stores all of these items in memory at once. For short sequences, this seems to be a rather paltry savings; this is not the case for long sequences. The following graph compares the memory consumption used when defining a generator for the sequence of numbers $0-N$ using `range`, compared to storing the sequence in a list: +因为 `range` 是一个生成器,指令 `range(5)` 仅仅只会存储用来生成数字0-4序列的指示。这和会同时在内存中存储所有数字的列表 `[0, 1, 2, 3, 4]` 不同。对短列表而言,这样做节省的内存可能很不可观,但是在处理长序列这就很重要了。以下的图表对比了使用 `range` 来定义一个生成数字序列 $0-N$ 和使用列表存储该序列的内存使用情况: ![Memory consumption figure](attachments/Mem_Consumption_Generator.png) -Given our discussion of generators, it should make sense that the memory consumed simply by defining `range(N)` is independent of $N$, whereas the memory consumed by the list grows linearly with $N$ (for large $N$). +根据上文对生成器的讨论,你应该理解为什么定义 `range(N)` 使用的内存和 $N$ 的大小无关,而列表使用的内存根据 $N$ 线性增长(假设 $N$ 比较大)。
-**Takeaway**: +**经验**: -`range` is a built-in generator, which generates sequences of integers. +`range` 是一个内置的生成器,其生成整数序列。
-**Reading Comprehension: Using `range`**: +**阅读理解:使用 `range`**: -Using `range` in a for-loop, print the numbers 10-1, in sequence. +在一个for循环中使用 `range` 来打印数字10-1(按此顺序)。
-## Creating your own generator: generator comprehensions -Python provides a sleek syntax for defining a simple generator in a single line of code; this expression is known as a **generator comprehension**. The following syntax is extremely useful and will appear very frequently in Python code: +## 创建你自己的生成器:生成器理解 +Python提供了一个轻便的用一行代码定义简单生成器的语法;这种表达式叫做*生成器理解*(generator comprehension)。以下语法极其有用,且在Python代码中非常常见:
-**Definition**: +**定义**: -The syntax +语法
`( for in [if ])`
-specifies the general form for a **generator comprehension**. This produces a generator, whose instructions for generating its members are provided within the parenthetical statement. +描述了**生成器理解**的一般形式。这将创建一个生成器,其生成成员的指示由括号中的语句提供。
-Written in a long form, the pseudo-code for +用伪代码来写,以下代码 ``` ( for in if ) ``` -is: +的长形式为: ``` for in : @@ -127,37 +127,37 @@ for in : yield ``` -The following expression defines a generator for all the even numbers in 0-99: +以下的表达式定义了一个0-99之间所有偶数的生成器: ```python -# when iterated over, `even_gen` will generate 0.. 2.. 4.. ... 98 +# 当被迭代时,`even_gen` 将生成 0.. 2.. 4.. ... 98 even_gen = (i for i in range(100) if i%2 == 0) ``` -The `if ` clause in the generator expression is optional. The generator comprehension +生成器中的 `if ` 句段是可选的。以下的生成器理解 ``` ( for in ) ``` -corresponds to: +对应着: ``` for in : yield ``` -For example: +比如说: ```python -# when iterated over, `example_gen` will generate 0/2.. 9/2.. 21/2.. 32/2 +# 当被迭代时,`example_gen` 将生成 0/2.. 9/2.. 21/2.. 32/2 example_gen = (i/2 for i in [0, 9, 21, 32]) for item in example_gen: print(item) -# prints: 0.0.. 4.5.. 10.5.. 16.0 +# 打印:0.0.. 4.5.. 10.5.. 16.0 ``` -`` can be any valid single-line of Python code that returns an object: +`` 可以是任何合法的返回单个对象的单行Python代码: ```python ((i, i**2, i**3) for i in range(10)) -# will generate: +# 会生成: # (0, 0, 0) # (1, 1, 1) # (2, 4, 8) @@ -170,7 +170,7 @@ for item in example_gen: # (9, 81, 729) ``` -This means that `` can even involve inline if-else statements! +这意味着 `` 甚至可以使用单行的if-else语句! ```python (("apple" if i < 3 else "pie") for i in range(6)) # will generate: @@ -184,93 +184,91 @@ This means that `` can even involve inline if-else statements!
-**Takeaway**: +**经验**: -A generator comprehension is a single-line specification for defining a generator in Python. It is absolutely essential to learn this syntax in order to write simple and readable code. +生成器理解是Python单行定义生成器的语法。这个语法对于编写简单和易读的代码是不可替代的。
-**Note**: +**注**: -Generator comprehensions are **not** the only method for defining generators in Python. One can define a generator similar to the way one can define a function (which we will encounter soon). [See this section of the official Python tutorial](https://docs.python.org/3/tutorial/classes.html#generators) if you are interested in diving deeper into generators. +生成器理解并*不是*唯一定义Python生成器的方法。你可以用类似定义函数(我们会在后文讨论)的方法定义生成器。[详见本节Python官方教程](https://docs.python.org/3/tutorial/classes.html#generators)来深入了解生成器。
-
-**Reading Comprehension: Writing a Generator Comprehension**: +**阅读理解:编写生成器理解**: -Using a generator comprehension, define a generator for the series: +使用生成器理解,定义一个会生成以下序列的生成器: ``` (0, 2).. (1, 3).. (2, 4).. (4, 6).. (5, 7) ``` -Note that (3, 5) is *not* in the series. +注意 (3, 5) 并*不*在序列中。 -Iterate over the generator and print its contents to verify your solution. +迭代该生成器并打印其内容以确认你的答案。
- -### Storing generators -Just like we saw with the `range` generator, defining a generator using a comprehension does *not* perform any computations or consume any memory beyond defining the rules for producing the sequence of data. See what happens when we try to print this generator: +### 存储生成器 +就像 `range` 一样,利用生成器理解来定义生成器*不会*进行任何运算或使用除了储存生成数据序列的规则之外的内存。请注意我们打印此生成器时会发生什么: ```python -# will generate 0, 1, 4, 9, 25, ..., 9801 +# 将会生成 0, 1, 4, 9, 25, ..., 9801 >>> gen = (i**2 for i in range(100)) >>> print(gen) at 0x000001E768FE8A40> ``` -This output simply indicates that `gen` stores a generator-expression at the memory address `0x000001E768FE8A40`; this is simply where the instructions for generating our sequence of squared numbers is stored. `gen` will not produce any results until we iterate over it. For this reason, generators cannot be inspected in the same way that lists and other sequences can be. You **cannot** do the following: +此输入仅仅显示 `gen` 在内存位置 `0x000001E768FE8A40` 存储了一个生成器;这仅仅是存储生成平方数指示的内存位置。`gen` 在我们迭代它之前并不会生成任何结果。因此,你无法像查看列表和其它序列一样来查看生成器。以下的代码**不合法**: ```python -# you **cannot** do the following... +# 以下的行为**不合法** >>> gen = (i**2 for i in range(100)) -# query the length of a generator +# 检查生成器的长度 >>> len(gen) TypeError: object of type 'generator' has no len() -# index into a generator +# 索引生成器 >>> gen[2] TypeError: 'generator' object is not subscriptable ``` -The sole exception to this is the `range` generator, for which all of these inspections are valid. +以上规则唯一的例外就是 `range` 生成器。你可以对它进行以上的操作。 -### Consuming generators -We can feed this to any function that accepts iterables. For instance, we can feed `gen` to the built-in `sum` function, which sums the contents of an iterable: +### 消耗生成器 +我们可以将生成器输入到任何接受可迭代数的函数中。比如说,我们可以将 `gen` 输入到内置的 `sum` 函数中。该函数会求可迭代物成员的和: ```python >>> gen = (i**2 for i in range(100)) ->>> sum(gen) # computes the sum 0 + 1 + 4 + 9 + 25 + ... + 9801 +>>> sum(gen) # 求和:0 + 1 + 4 + 9 + 25 + ... + 9801 328350 ``` -This computes the sum of the sequence of numbers *without ever storing the full sequence of numbers in memory*. In fact, only two numbers need be stored during any given iteration of the sum: the current value of the sum, and the number being added to it. +这在*从来不在内存中储存整个数字序列*的情况下计算以上数据序列的和。事实上,在任何一轮迭代中,Python只需要存储两个数字:到这一步为止的和以及下一步要加的数字。 -What happens if we run this command a second time: +如果我们第二次执行这个命令: ```python -# computes the sum of ... nothing! -# `gen` has already been consumed! +# 求和...为空! +# `gen` 已经被消耗了! >>> sum(gen) 0 ``` -It may be surprising to see that the sum now returns 0. This is because **a generator is exhausted after it is iterated over in full**. You must redefine the generator if you want to iterate over it again; fortunately, defining a generator requires very few resources, so this is not a point of concern. +你可能惊讶于sum现在返回0这一事实。这是因为**当生成器被完全迭代后它会消耗殆尽**。你必须重新定义该生成器来再次迭代它;幸运得是,定义一个生成器花的资源很少,所以你不需要去担心资源需求。 -You can also check for membership in a generator, but this also consumes the generator: +你也可以检查某对象是否属于生成器的一部分,但这么做会消耗(consume)这个生成器: ```python -# checking for membership consumes a generator until -# it finds that item (consuming the entire generator -# if the item is not contained within it) +# 检查某个对象是否为生成器成员会消耗生成器 +# 直到对象被找到(如果对象不为生成器成员, +# 那整个生成器都会被消耗) >>> gen = (i for i in range(1, 11)) ->>> 5 in gen # first 5 elements are consumed +>>> 5 in gen # 前5个成员被消耗 True -# 1-5 are no longer contained in gen -# this check consumes the entire generator! +# 1-5 已经不在 `gen` 中了 +# 因此这个检查会消耗整个生成器! >>> 5 in gen False @@ -280,28 +278,31 @@ False
-**Takeaway**: +**经验**: -A generator can only be iterated over once, after which it is exhausted and must be re-defined in order to be iterated over again. +生成器只能被迭代一次。在这之后它会被消耗殆尽。你必须要重新定义新的生成器来再次迭代。
-### Chaining comprehensions -Because generators are iterables, they can be fed into subsequent generator comprehensions. That is, they can be "chained" together. +### 连锁理解 +因为生成器是可迭代物,你可以将它们输入到另一层的生成器理解中。也就是说你在“连锁”(chain)它们。 ```python -# chaining two generator comprehensions +# 连锁两个生成器理解 -# generates 400.. 100.. 0.. 100.. 400 +# 生成 400.. 100.. 0.. 100.. 400 >>> gen_1 = (i**2 for i in [-20, -10, 0, 10, 20]) -# sums the generated numbers, excluding any numbers whose absolute value is greater than 150 ->>> sum(j for j in gen_1 if abs(j) <= 150) +# 迭代 `gen_1`,除去任何绝对值大于150的值 +>>> gen_2 = (j for j in gen_1 if abs(j) <= 150) + +# 计算 100 + 0 + 100 +>>> sum(gen_2) 200 ``` -This is equivalent to: +这等值于: ```python total = 0 @@ -310,13 +311,13 @@ for i in [-20, -10, 0, 10, 20]: if j <= 150: total += j -# total is now 200 +# `total` 现在是200 ``` -### Using generator comprehensions on the fly -A feature of Python, that can make your code supremely readable and intuitive, is that generator comprehensions can be fed *directly* into functions that operate on iterables. That is, +### 直接使用生成器理解 +Python支持你*直接*将生成器理解输入进使用可迭代物的函数。这将使你的代码极其可读易懂。比如说: ```python >>> gen = (i**2 for i in range(100)) @@ -324,23 +325,22 @@ A feature of Python, that can make your code supremely readable and intuitive, i 328350 ``` -can be simplified as: +可以被简化为: ```python >>> sum(i**2 for i in range(100)) 328350 ``` -If you want your code to compute the finite harmonic series: $\sum_{k=1}^{100} \frac{1}{n} = 1 + \frac{1}{2} + ... + \frac{1}{100}$, you can simply write: +如果你想要你的代码来计算有限的谐波系列:$\sum_{k=1}^{100} \frac{1}{n} = 1 + \frac{1}{2} + ... + \frac{1}{100}$,你可以直接写: ```python >>> sum(1/n for n in range(1, 101)) 5.187377517639621 ``` -This convenient syntax works for any function that expects an iterable as an argument, such as the `list` function and `all` function: +这方便的语法可以在任何使用可迭代物的函数中作为输入,如 `list` 函数和 `all` 函数: ```python -# providing generator expressions as arguments to functions -# that operate on iterables +# 将生成器表达式直接输入进使用可迭代物的函数中 >>> list(i**2 for i in range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] @@ -352,26 +352,26 @@ True ```
-**Takeaway**: +**经验**: -A generator comprehension can be specified directly as an argument to a function, wherever a single iterable is expected as an input to that function. +你可以将生成器理解语句直接作为任何需要可迭代物的函数输入。
-**Reading Comprehension: Using Generator Comprehensions on the Fly**: +**阅读理解:直接使用生成器理解**: -In a single line, compute the sum of all of the odd-numbers in 0-100. +在一行内计算0-100之间所有奇数之和。
-## Iterating over generators using `next` -The built-in function `next` allows you manually "request" the next member of a generator, or more generally, any kind of *iterator*. Calling `next` on an exhausted iterator will raise a `StopIteration` signal. +## 使用 `next` 迭代生成器 +内置函数 `next` 允许我们手动“请求”生成器(或任何*迭代器*(iterator))的下一个成员。对一个消耗殆尽的迭代器调用 `next` 会导致 `StopIteration` 信号。 ```python -# consuming an iterator using `next` +# 使用 `next` 消耗迭代器 >>> short_gen = (i/2 for i in [1, 2, 3]) >>> next(short_gen) @@ -392,22 +392,21 @@ Traceback (most recent call last) StopIteration: ``` -This is a great tool for retrieving content from a generator, or any iterator, without having to perform a for-loop over it. +这方便你在不使用for循环的情况下获取生成器或任何迭代器的成员。 -### Iterables vs. Iterators -This subsection is *not* essential to your basic understanding of the material. I am including it to prevent this text from being misleading to those who already know quite a bit about Python. **This is a bit advanced, feel free to skip it...** +### 可迭代物 vs. 迭代器 +本小节并不是理解本资源的*关键*内容。包含本小节的目的是为了不误导已经对Python有一些了解的读者。**本小节内容比较深入,请随意跳过……** -There is a bit of confusing terminology to be cleared up: an iterable is not the same thing as an iterator. +让我们来解释清楚一些易混的术语:可迭代物和迭代器是不一样的。 -An *iterator* object stores its current state of iteration and "yields" each of its members in order, on demand via `next`, until it is exhausted. As we've seen, a generator is an example of an iterator. We now must understand that every iterator is an iterable, but not every iterable is an iterator. +一个*迭代器*对象存储着迭代过程当前的内态,并在收到通过 `next` 提出的请求时顺序“提供”(yield)它的成员,直到它消耗殆尽。像我们所见,生成器是迭代器的一种。请注意,每一个迭代器都是可迭代物,但不是每一个可迭代物都是迭代器。 -An *iterable* is an object that *can* be iterated over but does not necessarily have all the machinery of an iterator. For example, sequences (e.g lists, tuples, and strings) and other containers (e.g. dictionaries and sets) do not keep track of their own state of iteration. Thus you cannot call `next` on one of these outright: +一个*可迭代物*是任何*可以*被迭代的对象,但它不一定有着迭代器全部的功能。比如说,序列(如列表,元组,和字符串)和其它容器(如词典和集)并不会存储其迭代过程的内态。因此你不能直接对其调用 `next`: ```python -# a list is an example of an iterable that is *not* -# an iterator - you cannot call `next` on it. +# 列表是可迭代物,但*不是*迭代器——你不能对其调用 `next`。 >>> x = [1, 2, 3] >>> next(x) --------------------------------------------------------------------------- @@ -417,12 +416,12 @@ TypeError Traceback (most recent call last) TypeError: 'list' object is not an iterator ``` -In order to iterate over, say, a list you must first pass it to the built-in `iter` function. This function will return an *iterator* for that list, which stores its state of iteration and the instructions to yield each one of the list's members: +为了迭代如列表这样的可迭代物,你必须先将其输入到内置的 `iter` 函数中。这个函数会返回该列表的一个*迭代器*,其存储着它迭代的内态以及提供列表每一个成员的指示: ```python -# any iterable can be fed to `iter` -# to produce an iterator for that object +# 任何可迭代物都可以被输入进 `iter` 中 +# 来得到该对象的一个迭代器 >>> x = [1, 2, 3] ->>> x_it = iter(x) # `x_it` is an iterator +>>> x_it = iter(x) # `x_it` 是一个迭代器 >>> next(x_it) 1 >>> next(x_it) @@ -430,29 +429,29 @@ In order to iterate over, say, a list you must first pass it to the built-in `it >>> next(x_it) 3 ``` -In this way, a list is an *iterable* but not an *iterator*, which is also the case for tuples, strings, sets, and dictionaries. +所以说列表是*可迭代物*但不是*迭代器*。这一点和元组,字符串,集,和词典一样。 -Python actually creates an iterator "behind the scenes", whenever you perform a for-loop over an iterable like a list. It feeds that iterable to `iter`, and then proceeds to call `next` on the resulting iterator for each of the for-loop's iterations. +每当你for循环一个如列表的迭代器时,Python其实都会在“幕后”创建一个迭代器。它将可迭代物输入进 `iter` 中,并在for循环每轮迭代时对返回的迭代器调用 `next`。 -## List & Tuple Comprehensions -Using generator comprehensions to initialize lists is so useful that Python actually reserves a specialized syntax for it, known as the list comprehension. A **list comprehension** is a syntax for constructing a list, which exactly mirrors the generator comprehension syntax: +## 列表和元组理解 +因为使用生成器理解来初始化列表的流程极其有用,Python专门为其定义了专门的语法,叫做列表理解(list comprehension)。**列表理解**是一种创建列表的语法,和生成器理解语法完全类似: ``` [ for in {if >> [i**2 for i in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ``` -This produces the exact same result as feeding the `list` function a generator comprehension. However, using a list comprehension is slightly more efficient than is feeding the `list` function a generator comprehension. +这将创建和对生成器理解输入调用 `list` 函数一样的结果。但是,使用列表理解比将生成器理解输入到 `list` 中稍微更高效一点。 -Let's appreciate how economical list comprehensions are. The following code stores words that contain the letter "o", in a list: +让我们来体会一下列表理解的实惠之处。以下代码将在一个列表中储存包含字母“o”的字符串: ```python words_with_o = [] word_collection = ['Python', 'Like', 'You', 'Mean', 'It'] @@ -462,7 +461,7 @@ for word in word_collection: words_with_o.append(word) ``` -This can be written in a single line, using a list comprehension: +你可以使用列表理解来将以上代码在一行中实现: ```python >>> word_collection = ['Python', 'Like', 'You', 'Mean', 'It'] >>> words_with_o = [word for word in word_collection if "o" in word.lower()] @@ -470,27 +469,27 @@ This can be written in a single line, using a list comprehension: ['Python', 'You'] ``` -Tuples can be created using comprehension expressions too, but we must explicitly invoke the `tuple` constructor since parentheses are already reserved for defining a generator-comprehension. +你也可以用理解语句来创建元组,但是你必须要使用 `tuple` 构造器来做到这一点,因为括号已经为生成器理解保留了。 ```python -# creating a tuple using a comprehension expression +# 使用理解表达式来创建元组 >>> tuple(i**2 for i in range(5)) (0, 1, 4, 9, 16) ```
-**Takeaway**: +**经验**: - The comprehensions-statement is an extremely useful syntax for creating simple and complicated lists and tuples alike. +理解语句是对创建简单或复杂的列表或元组都极其有用的语法。
-### Nesting comprehensions -It can be useful to nest comprehension expressions within one another, although this should be used sparingly. +### 嵌套理解语句 +你可以在一个理解表达式中嵌套(nest)另外一个理解表达式,但请注意不要滥用这一功能。 ```python -# Nested list comprehensions. -# This creates a 3x4 "matrix" (list of lists) of zeros. +# 嵌套列表理解。 +# 这创建了一个大小为3x4,内容为0的的“矩阵”(存有多个列表的列表)。 >>> [[0 for col in range(4)] for row in range(3)] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` @@ -498,18 +497,18 @@ It can be useful to nest comprehension expressions within one another, although
-**Reading Comprehension: List Comprehensions**: +**阅读理解:列表理解**: -Use a list comprehension to create a list that contains the string "hello" 100 times. +使用列表理解来的创建一个包含100个字符串“hello”的列表。
-**Reading Comprehension: Fancier List Comprehensions**: +**阅读理解:高级的列表理解**: -Use the inline `if-else` statement (discussed earlier in this module), along with a list comprehension, to create the list: +使用单行的 `if-else` 语句(在本模组前文讨论过)以及列表理解来创建以下列表: ```python ['hello', @@ -529,22 +528,22 @@ Use the inline `if-else` statement (discussed earlier in this module), along wit
-**Reading Comprehension: Tuple Comprehensions**: +**阅读理解:元组理解**: -Use a tuple-comprehension to extract comma-separated numbers from a string, converting them into a tuple of floats. I.e. `"3.2,2.4,99.8"` should become `(3.2, 2.4, 99.8)`. You will want to use the built-in string function [str.split](https://docs.python.org/3/library/stdtypes.html#str.split). +使用元组理解来提取字符串中由逗号隔开的数字,并将它们转化成一个浮点数元组。比如说,`"3.2,2.4,99.8"` 应被转化成 `(3.2, 2.4, 99.8)`。你应该会想要使用内置的字符串函数[str.split](https://docs.python.org/3/library/stdtypes.html#str.split)。
-**Reading Comprehension: Translating a For-Loop**: +**阅读理解:翻译for循环**: -Replicate the functionality of the the following code by writing a list comprehension. +使用列表理解来复制以下代码的功能。 ```python -# skip all non-lowercased letters (including punctuation) -# append 1 if lowercase letter is "o" -# append 0 if lowercase letter is not "o" +# 跳过所有非小写字母(包括标点符号) +# 如果小写字母是“o”,在列表结尾添加1 +# 如果小写字母不是“o”,在列表结尾添加0 out = [] for i in "Hello. How Are You?": if i.islower(): @@ -557,84 +556,91 @@ for i in "Hello. How Are You?":
-**Reading Comprehension: Memory Efficiency**: +**阅读理解:内存效率**: -Is there any difference in performance between the following expressions? +以下两个表达式的效率有任何区别么? ```python -# feeding `sum` a generator comprehension +# 将生成器理解输入到 `sum` 中 sum(1/n for n in range(1, 101)) ``` ```python -# feeding `sum` a list comprehension +# 将列表理解输入到 `sum` 中 sum([1/n for n in range(1, 101)]) ``` -Is one expression preferable over the other? Why? +以上有一个表达式优于另外一个吗?为什么?
-## Links to Official Documentation +## 官方说明文档链接 -- [Generator definition](https://docs.python.org/3/glossary.html#term-generator) +- [生成器定义](https://docs.python.org/3/glossary.html#term-generator) - [range](https://docs.python.org/3/library/stdtypes.html#typesseq-range) -- [Generator comprehension expressions](https://docs.python.org/3/tutorial/classes.html#generator-expressions) -- [Iterator definition](https://docs.python.org/3/glossary.html#term-iterator) +- [生成器理解表达式](https://docs.python.org/3/tutorial/classes.html#generator-expressions) +- [迭代器定义](https://docs.python.org/3/glossary.html#term-iterator) - [next](https://docs.python.org/3/library/functions.html#next) - [iter](https://docs.python.org/3/library/functions.html#iter) -- [List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) -- [Nested list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions) +- [列表理解](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) +- [嵌套列表理解](https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案: -**Using range: Solution** +**使用 `range`:解** ```python -# start=10, stop=0 (excluded), step-size=-1 -for i in range(10, 0, -1): - print(i) +# start=10,stop=0(不包含),step-size=-1 +>>> for i in range(10, 0, -1): +>>> print(i, end=" ") # “end”参数用来避免每个值都使用新行打印 +10 9 8 7 6 5 4 3 2 1 ``` -**Writing a Generator Comprehension: Solution** +**编写生成器理解:解** ```python -((n, n+2) for n in range(6) if n != 3) +>>> g = ((n, n+2) for n in range(6) if n != 3) +>>> list(g) # 转化成列表来打印其中的值 +[(0, 2), (1, 3), (2, 4), (4, 6), (5, 7)] ``` -**Using Generator Comprehensions on the Fly: Solution** +**直接使用生成器理解:解** ```python -sum(range(1, 101, 2)) +>>> sum(range(1, 101, 2)) +2500 ``` -or +或 ```python -sum(i for i in range(101) if i%2 != 0) +>>> sum(i for i in range(101) if i%2 != 0) +2500 ``` -**List Comprehensions: Solution** +**列表理解:解** ```python -["hello" for i in range(100)] +>>> ["hello" for i in range(100)] +['hello', 'hello', ..., 'hello', 'hello'] # 100个hello ``` -**Fancier List Comprehensions: Solution** +**高级的列表理解:解** ```python -[("hello" if i%2 == 0 else "goodbye") for i in range(10)] +>>> [("hello" if i%2 == 0 else "goodbye") for i in range(10)] +['hello', 'goodbye', 'hello', 'goodbye', 'hello', 'goodbye', 'hello', 'goodbye', 'hello', 'goodbye'] ``` -**Tuple Comprehension: Solution** +**元组理解:解** ```python >>> string_of_nums = "3.2, 2.4, 99.8" >>> tuple(float(i) for i in string_of_nums.split(",")) @@ -643,12 +649,14 @@ sum(i for i in range(101) if i%2 != 0) -**Translating a For-Loop: Solution** +**翻译for循环:解** ```python -out = [(1 if i is "o" else 0) for i in "Hello. How Are You?" if i.islower()] +>>> out = [(1 if i is "o" else 0) for i in "Hello. How Are You?" if i.islower()] +>>> out +[0, 0, 0, 1, 1, 0, 0, 0, 1, 0] ``` -**Memory Efficiency: Solution** +**内存效率:解** -It is preferable to use the generator expression `sum(1/n for n in range(1, 101))`, rather than the list comprehension `sum([1/n for n in range(1, 101)])`. Using a list comprehension unnecessarily creates a list of the one hundred numbers, in memory, before feeding the list to `sum`. The generator expression need only produce a single value at a time, as `sum` iterates over it. +生成器表达式 `sum(1/n for n in range(1, 101))` 比起列表理解 `sum([1/n for n in range(1, 101)])` 更优。使用列表理解会不必要的在内存中创建有100个数字的列表,然后再将其输入到 `sum` 中。生成器表达式则在 `sum` 迭代时每次只生成一个数值。 diff --git a/Python/Module2_EssentialsOfPython/Introduction.md b/Python/Module2_EssentialsOfPython/Introduction.md index 6bbf1be..ebac399 100644 --- a/Python/Module2_EssentialsOfPython/Introduction.md +++ b/Python/Module2_EssentialsOfPython/Introduction.md @@ -4,148 +4,141 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: introduction to control flow, Difficulty: Easy, Category: Section :keywords: overview, summary, if, else, function, for-loop, if, else, control flow -``` + -# Introducing Control Flow -Very simply put, to "control flow" in your code is to affect the order in which the -code in your program is executed. Up until this point in the course, you have seen (and hopefully written) code that -executes linearly; for example: +# 控制流简介 +简单来讲,“控制”你代码的“流程”(control flow)就是去影响你程序中代码执行的顺序。到现在为止,本文中的所有代码都是线性执行的;比如说: ```python -# simple code without any "control flow" -# i.e. no branches in logic, loops, or -# code encapsulation +# 没有任何“控制流”的简单代码,也就是说, +# 代码没有任何逻辑分枝,循环,或代码包装 x = 6 y = 23 print("x + y = ", x + y) print("x - y = ", x - y) ``` -But what if you want your code to do something different when `x` is an even number? What if you want to do an additional computation for every number that falls between `x` and `y`? By the end of this module, you should understand how to write programs that can accommodate these, and many other, branches in logic. +但假如你想要让你的代码在 `x` 是偶数时有着不同的行为呢?或者假设你想要为 `x` 和 `y` 之中的所有数字做一些计算呢?在本模组结尾,你应该会理解如何编写代码来提供这些和其它更多的逻辑分枝。 -Control flow tools will vastly expand your ability to write useful code. They are the quintessential building blocks for modern programming languages, and are effectively the same across Python, C, C++, Java, and many others (barring syntactic differences). +控制流工具将会极大地提升你编写实用代码的能力。它们是现代编程语言经典的成分,因此它们在Python,C,C++,Java,和其它很多编程语言中的功能都差不多(语法区别除外)。 -As a sneak peek, let's write a function that counts how many numbers between m and n are divisible by 3 +作为一个预览,让我们编写一个返回 m 和 n 之间有多少个可以被3整除的数字的函数: ```python def cnt_div_by_3(m, n): - """ Counts how many numbers in the interval [m, n] are divisible by 3. """ + """ 返回在 [m, n] 中有多少被3整除的数字。""" count = 0 for num in range(m, n + 1): - if num % 3 == 0: # recall: x % y gives the remainder of x / y + if num % 3 == 0: # 请回忆:x % y 会提供 x / y 的余数 count += 1 else: - pass # this `else-pass` statement is not really necessary - # it is included for the sake of clarity in this introduction + pass # 这个 `else-pass` 语句其实并没有必要 + # 我们仅仅为了此简介的清晰解释在此包含 return count ``` -(note: there are much more efficient ways of computing this - can you think of any?) +(注:我们有其它有效率高很多的方法来计算这个结果——你可以想到任何方法吗?) -This code contains several critical "control flow" features: +此代码包含着几个很重要的“控制流”特征: -- The `def cnt_div_by_3(m, n):` statement signals the definition of a function: a modular block of code, which can be utilized elsewhere in your code. -- The line `for num in range(m, n + 1):` signifies a "for-loop" which instructs the code to iterate over a sequence of numbers, executing a common block of code for each iteration. -- `if num % 3 == 0:` and `else` instruct pieces of codes to be executed conditionally - only if a specified condition is met. +- 语句 `def cnt_div_by_3(m, n):` 定义一个函数:可以在程序其它地方调用的模组化的代码块。 +- `for num in range(m, n + 1):` 这行则示意一个for循环,让代码迭代一序列的数字并每轮执行同一组代码。 +- `if num % 3 == 0:` 和 `else` 指示程序有条件执行代码片段——也就是在特定条件满足时才执行。 -In the following sections, you will be formally introduced to if-elif-else blocks, for-loops & iterables, and functions, all so that you can implement effective "control flow" in your code. +在下文的节中,你将会正式地学习if-elif-else组,for循环和可迭代对象,以及函数来帮助你在代码中执行有效的控制流。 -Before embarking on these sections, we must take a moment to study Python's syntax for delimiting scope for these various control flow constructs. +在深入讨论这些内容之前,让我们花一些时间来学习Python限定不同控制流结构体区域的语法。 -## Python Uses Whitespace to Delimit Scope +## Python使用空格来限定区域 -While the concepts of function definitions, loops, and conditional statements are shared across the majority of modern programming languages, the languages often differ in their syntax for delimiting the *bodies* of these constructs. For example, where C++ uses "curly braces" as delimiters, e.g.: +虽然这些函数定义,循环,和有条件执行的语句在大部分现代编程语言通用,这些语言的语法区别经常在于它们限定控制流结构体*主体*的方法。比如说,C++使用弯括号来限定逻辑区块,如: ```cpp -// example showing that C++ uses curly braces to delimit scope +// 演示C++使用弯括号来限定区域 int x = 1; if (x > 10) { - // we are inside the if-block, as delimited by the curly-brackets + // 我们在的if区块被弯括号限定包围(限定) x = x + 1; } -// we are outside of the if-block +// 我们现在在if区块外面 x = x + 3; ``` -Python **uses whitespace (i.e. indentation) to delimit scope**: +Python**使用空格(也就是缩进)来限定区域(scope)**: ```python -# example showing that Python uses whitespace to delimit scope +# 演示Python使用空格来限定区域 x = 1 if x > 10: - # we are inside the if-block; this line starts with four blank spaces + # 我们在一个if区块中;此行由4个空格打头 x = x + 1 -# we are outside of the if-block; there are no leading whitespace characters +# 我们现在在if区块外面;这里没有任何空格打头 x = x + 3 ``` -Look to the example at the beginning of this section to see the bodies of the function definition, the for-loop, and the subsequent if-else block were all separated by increasing levels of indentation. +看一下本节开始的范例并注意其函数定义,for循环,和里面的if-else区块都由逐渐增加的缩进来区分。 -Python's syntax is quite flexible in terms of what it defines as a whitespace delimiter. Its rules are that: +Python的语法对空格限定符的定义比较宽松。它的规则为: -- One or more whitespace characters (spaces or tabs) is sufficient to serve as indentation. -- A given indented block must use a uniform level of indentation. E.g. if the first line of an indented block has two leading spaces, all subsequent lines in that block must lead with exactly two white spaces. +- 一个或更多的空符(空格和tab)足以作为缩进。 +- 一个有缩进的区块的每一行必须使用同样的缩进级别。比如说,如果有缩进的区块的第一行有两个打头的空格,那么此区块之后的每一行都要由两个空格打头。 -While Python's syntax is relatively forgiving, I am not: the [standard style](https://www.python.org/dev/peps/pep-0008/#indentation) for indenting in Python is to **use four space characters** for each level of indentation. It is strongly advised that you adhere to this standard. Most IDEs and consoles (including Jupyter notebooks) will automatically add a four-space indentation for you when you enter into the body of one of the aforementioned constructs. +虽然Python的语法比较宽松,但我并不如此:Python缩进的[标准风格](https://www.python.org/dev/peps/pep-0008/#indentation) 是每一层**使用四个空格**。我强烈建议你遵循这个标准。大部分的IDE和命令行(包括Jupyter记事本)会自动在你进入某个以上的构造体时为你增加四个空格的缩进。 -Let's review these ruled by considering a few simple examples (including incorrect examples) of delimiting scope in Python. +让我们通过几个例子(包括错误的例子)来复习一下在Python中限定区域的规则。 ```python -# OK, but gross: The use of a single whitespace -# makes the indentation hard to see. Use four spaces. +# 可以,但很恶心:使用一个空格使得缩进很难看清。用四个空格 if True: - x = 1 # one space - y = 2 # one space + x = 1 # 一个空格 + y = 2 # 一个空格 ``` ```python -# BAD: the inconsistent level of indentation in this -# single block will cause this code to raise an IndentationError +# 不合法:在一个区块中使用多个级别的缩进会导致 IndentationError def my_func(x): - x = x + 1 # four spaces - y = 3 # eight spaces - z = x + y # four spaces - return z # four spaces + x = x + 1 # 四个空格 + y = 3 # 八个空格 + z = x + y # 四个空格 + return z # 四个空格 ``` ```python -# OK, but gross: The if-block uses four spaces as a delimiter. -# The else-block uses two spaces as a delimiter. This is technically -# okay since indentation is consistent within each block. One should -# always use four spaces for indentation. +# 可以,但很恶心:if区块使用四个空格来限定。而else区块使用两个空格 +# 来限定。这虽然合法(因为在每个区块中的缩进相同),但是你应该永远 +# 使用四个空格来缩进 if True: - x = 3 # four spaces - y = 2 # four spaces + x = 3 # 四个空格 + y = 2 # 四个空格 else: - x = 2 # two spaces - y = 1 # two spaces + x = 2 # 两个空格 + y = 1 # 两个空格 ``` ```python -# Good! The for-loop's body is defined by one level -# of four-space indentation, and the contained if-else -# blocks each have their own additional four-space indentations. +# 棒棒的!for循环的主体由一层的四空格的缩进定义,而其中的if-else +# 区块有着自己的额外的四空格缩进。 for i in [1, 2, 3, 4]: - if i == 2 or i == 4: # four spaces - x = "even" # eight spaces - else: # four spaces - x = "odd" # eight spaces + if i == 2 or i == 4: # 四个空格 + x = "even" # 八个空格 + else: # 四个空格 + x = "odd" # 八个空格 ``` diff --git a/Python/Module2_EssentialsOfPython/Iterables.md b/Python/Module2_EssentialsOfPython/Iterables.md index 5eb7fc4..db11bfb 100644 --- a/Python/Module2_EssentialsOfPython/Iterables.md +++ b/Python/Module2_EssentialsOfPython/Iterables.md @@ -4,55 +4,55 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: the basics of iterables in python, Difficulty: Medium, Category: Section :keywords: iterables, max, min, sum, all, any, itertools, enumerate, unpack -``` + -# Iterables -Our encounter with for-loops introduced the term *iterable* - an object that can be "iterated over", such as in a for-loop. +# 可迭代物 +我们之前在讨论for循环的时候介绍了*可迭代物*(iterable)——也就是任何你可以“迭代”(如for循环)的对象。
-**Definition**: +**定义**: -An **iterable** is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. +**可迭代物**泛指任何支持一次返回一个成员的Python对象。这使得它可以用for循环迭代。
-Familiar examples of iterables include lists, tuples, and strings - any such sequence can be iterated over in a for-loop. We will also encounter important non-sequential collections, like dictionaries and sets; these are iterables as well. It is also possible to have an iterable that "generates" each one of its members upon iteration - meaning that it doesn't ever store all of its members in memory at once. We dedicate an entire section to generators, a special type of iterator, because they are so useful for writing efficient code. +常见的可迭代物包括列表,元组,和字符串——任何你可以用for循环迭代的序列(sequence)。我们也将遇到一些并非序列的集合,如词典(dictionary)和集(set);这些也是可迭代物。Python也提供在每轮迭代时“生成”(generate)一个成员的可迭代物——也就是说它甚至不需要同时在内存中存储所有的成员。我们会在后文花一整节来讨论生成器(generator)——一种特殊的迭代器——因为它们会帮助我们编写高效率的代码。 -The rest of this section is dedicated to working with iterables in your code. +本节将会讨论如何在你的代码中使用可迭代物。
-**Note**: +**注**: -"Under the hood", an iterable is any Python object with an `__iter__()` method or with a `__getitem__()` method that implements `Sequence` semantics. These details will become salient if you read through the Object Oriented Programming module. +在“幕后”,可迭代物是任何提供 `__iter__()` 方法(method)或实现了 `Sequence` 语义的 `__getitem__()` 方法的Python对象。在你阅读面向对象模组时,这些细节将会更加显著。
-## Functions that act on iterables -Here are some useful built-in functions that accept iterables as arguments: - - - `list`, `tuple`, `dict`, `set`: construct a list, tuple, [dictionary](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html), or [set](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#The-%E2%80%9CSet%E2%80%9D-Data-Structure), respectively, from the contents of an iterable - - `sum`: sum the contents of an iterable. - - `sorted`: return a list of the sorted contents of an interable - - `any`: returns `True` and ends the iteration immediately if `bool(item)` was `True` for *any* item in the iterable. - - `all`: returns `True` only if `bool(item)` was `True` for *all* items in the iterable. - - `max`: return the largest value in an iterable. - - `min`: return the smallest value in an iterable. - +## 操作可迭代物的函数 +以下是一些有用的操作可迭代物的函数: + + - `list`, `tuple`, `dict`, `set`:利用可迭代物的成员来分别创建列表,元组,[词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html),或[集](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#集数据结构)。 + - `sum`:求可迭代物内容的和。 + - `sorted`:返回成员为可迭代物成员顺序排列版本的列表。 + - `any`:迭代可迭代物。如果可迭代物中*任何*(any)一个成员满足 `bool(item)` 为 `True`,立刻返回 `True` 并终止迭代。 + - `all`:只有在可迭代物中*所有*(all)成员都满足 `bool(item)` 为 `True` 时返回 `True`。 + - `max`:返回可迭代物中的最大值。 + - `min`:返回可迭代物中的最小值。 + ```python -# Examples of built-in functions that act on iterables +# 操作可迭代物内置函数的例子 >>> list("I am a cow") ['I', ' ', 'a', 'm', ' ', 'a', ' ', 'c', 'o', 'w'] @@ -62,11 +62,11 @@ Here are some useful built-in functions that accept iterables as arguments: >>> sorted("gheliabciou") ['a', 'b', 'c', 'e', 'g', 'h', 'i', 'i', 'l', 'o', 'u'] -# `bool(item)` evaluates to `False` for each of these items +# 以下所有物件都导致 `bool(item)` 为 `False` >>> any((0, None, [], 0)) False -# `bool(item)` evaluates to `True` for each of these items +# 以下所有物件都导致 `bool(item)` 为 `True` >>> all([1, (0, 1), True, "hi"]) True @@ -79,14 +79,14 @@ True -## Tricks for working with iterables -Python provides some syntactic "tricks" for working with iterables: "unpacking" iterables and "enumerating" iterables. Although these may seem like inconsequential niceties at first glance, they deserve our attention because they will help us write clean, readable code. Writing clean, readable code leads to bug-free algorithms that are easy to understand. Furthermore, these tricks will also facilitate the use of other great Python features, like comprehension-statements, which will be introduced in the coming sections. +## 操作可迭代物的技巧 +Python提供了一些用来操作可迭代物的一些语法上”技巧“:”解包“(unpack)和“枚举”(enumerate)。虽然这些功能一开始看起来像奇技淫巧,但是它们会帮助我们编写干净易读的代码和正确易懂的算法,因此我们会花一些时间去讨论它们。同时,这些技巧也会帮助我们使用其它棒棒的Python功能,如理解语句(comprehension statement)。我们会在后文进行讨论。 -### "Unpacking" iterables -Suppose that you have three values stored in a list, and that you want to assign each value to a distinct variable. Given the lessons that we have covered thus far, you would likely write the following code: +### “解包”可迭代物 +假设你的列表中存储了三个值,且你想要将每个值赋值给一个单独的变量。利用前文的知识点,你很可能会编写以下的代码: ```python -# simple script for assigning contents of a list to variables +# 将列表内容赋值给变量的简单脚本 >>> my_list = [7, 9, 11] >>> x = my_list[0] @@ -94,10 +94,10 @@ Suppose that you have three values stored in a list, and that you want to assign >>> z = my_list[2] ``` -Python provides an extremely useful functionality, known as **iterable unpacking**, which allows us to write the simple, elegant code: +Python提供一个极其有用的功能,叫做**可迭代物解包**(iterable unpacking)。它允许我们编写以下优雅,简单的代码: ```python -# assigning contents of a list to variables using iterable unpacking +# 使用可迭代物解包来赋值多个变量 >>> my_list = [7, 9, 11] >>> x, y, z = my_list @@ -105,40 +105,39 @@ Python provides an extremely useful functionality, known as **iterable unpacking 7 9 11 ``` -That is, the Python interpreter "sees" the pattern of variables to the left of the assignment, and will "unpack" the iterable (which happens to be a list in this instance). It may not seem like it from this example, but this is an *extremely* useful feature of Python that greatly improves the readability of code! +也就是说,Python直译器会“注意”赋值符左边的多个变量并以此“解包”右边的可迭代物(在此例中为一个列表)。虽然在本例中这个功能看起来没那么关键,但实际上它是一个*极其*有用的提升代码可读性的功能。 -Iterable unpacking is particularly useful in the context of performing for-loops over iterables-of-iterables. For example, suppose we have a list containing tuples of name-grade pairs: +在for循环成员为可迭代物的可迭代物时,可迭代物解包功能极其有用。比如说,假设我们有一列表的元组,每个元组包含一对名字和成绩: ```python >>> grades = [("Ashley", 93), ("Brad", 95), ("Cassie", 84)] ``` -Recall from the preceding section that if we loop over this list, that the iterate-variable will be assigned to each of these tuples: +根据上一节所述,如果我们循环此列表,那么每一轮迭代变量都会被赋值为其中的元组: ```python for entry in grades: print(entry) ``` -will print: +会打印: ``` ('Ashley', 93) ('Brad', 95) ('Cassie', 84) ``` -It is likely that we will want to work with the student's name and their grade independently (e.g. use the name to access a log, and add the grade-value to our class statistics); thus we will need to index into `entry` twice to assign its contents to two separate variables. However, because each iteration of the for-loop involves an assignment of the form `entry = ("Ashley", 93)`, we can make use of iterable unpacking! That is, we can replace `entry` with `name, grade` and Python will intuitively do an unpacking upon each assignment of the for-loop. +我们很有可能会想要单独使用学生的名字和成绩(比如说,使用学生名字来访问其成绩记录并添加对应的成绩);所以说,我们需要索引 `entry` 两次来获得两个不同的变量。但是,因为for循环每一轮的赋值步骤真的其实就是 `entry = ("Ashley", 93)`,我们可以使用可迭代物解包!也就是说,我们可以用 `name, grade` 来代替 `entry`。Python会为其中每个变量进行解包。 ```python -# The first iteration of this for-loop performs -# the unpacking assignment: name, grade = ("Ashley", 93) -# then the second iteration: name, grade = ("Brad", 95) -# and so-on +# 本for循环的第一次迭代会将赋值解包:name, grade = ("Ashley", 93) +# 然后第二次迭代:name, grade = ("Brad", 95) +# 如下反复 for name, grade in grades: print(name) print(grade) print("\n") ``` -prints: +打印: ``` Ashley 93 @@ -149,24 +148,24 @@ Brad Cassie 84 ``` -This for-loop code is concise and supremely readable. It is highly recommended that you make use of iterable unpacking in such contexts. +这个for循环代码简洁并非常可读。本文强烈推荐读者在这种情况下使用可迭代物解包。 -Iterable unpacking is not quite as simple as it might seem. What happens if you provide 4 variables to unpack into, but use an iterable containing 10 items? Although what we have covered thus far conveys the most essential use case, it is good to know that [Python provides an even more extensive syntax for unpacking iterables](https://www.python.org/dev/peps/pep-3132/#specification). We will also see that unpacking can be useful when creating and using functions. +可迭代物解包的行为有时并不如此易懂。假如你试图将一个有10个对象的可迭代物解包到4个变量时会发生什么?虽然我们之前讨论的内容概括了最基础的解包方式,知道[Python提供更加全面复杂的可迭代物解包语法](https://www.python.org/dev/peps/pep-3132/#specification)这一事实也是很有帮助的。我们会在之后看到解包在创建和使用函数时的用处。
-**Takeaway**: +**经验**: -Python provides a sleek syntax for "unpacking" the contents of an iterable - assigning each item to its own variable. This allows us to write intuitive, highly-readable code when performing a for-loop over a collection of iterables. +Python为“解包”(unpack)可迭代物内容——将每个成员赋值给它对应的变量——提供了轻便的语法。这允许我们在for循环可迭代物集合时编写易懂易读的代码。
-### Enumerating iterables -The built-in [enumerate](https://docs.python.org/3/library/functions.html#enumerate) function allows us to iterate over an iterable, while keeping track of the iteration count: +### 枚举可迭代物 +内置的[enumerate](https://docs.python.org/3/library/functions.html#enumerate)(枚举)函数允许我们在迭代时获取可迭代物成员在迭代过程中的位置: ```python -# basic usage of `enumerate` +# 简单使用 `enumerate` >>> for entry in enumerate("abcd"): ... print(entry) (0, 'a') @@ -175,77 +174,77 @@ The built-in [enumerate](https://docs.python.org/3/library/functions.html#enumer (3, 'd') ``` -In general, the `enumerate` function accepts an iterable as an input, and returns a new iterable that produces a tuple of the iteration-count and the corresponding item from the original iterable. Thus the items in the iterable are being enumerated. To see the utility of this, suppose that we want to record all of the positions in a list where the value `None` is stored. We can achieve this by tracking the iteration count of a for-loop over the list. +`enumerate` 函数接受一个可迭代物并返回一个新的可迭代物,其成员为包含迭代位置和对应成员的元组。如此,我们在枚举这个可迭代物的成员。为了演示此功能的用处,假设我们想要记录列表中所有成员值为 `None` 的索引。我们可以通过在for循环迭代列表时记录迭代位置来达到这个目的。 ```python -# track which entries of an iterable store the value `None` +# 记录可迭代物中值为 `None` 的成员的位置 none_indices = [] -iter_cnt = 0 # manually track iteration-count +iter_cnt = 0 # 手动记录迭代位置 for item in [2, None, -10, None, 4, 8]: if item is None: none_indices.append(iter_cnt) iter_cnt = iter_cnt + 1 -# `none_indices` now stores: [1, 3] +# `none_indices` 现在存储 [1, 3] ``` -We can simplify this code, and avoid having to initialize or increment the `iter_cnt` variable, by utilizing `enumerate` along with tuple-unpacking. +利用 `enumerate` 和元组解包,我们可以简化此代码并避免使用 `iter_cnt` 这个变量。 ```python -# using the `enumerate` function to keep iteration-count +# 使用 `enumerate` 函数来记录迭代位置 none_indices = [] -# note the use of iterable unpacking! +# 请注意这里的可迭代物解包! for iter_cnt, item in enumerate([2, None, -10, None, 4, 8]): if item is None: none_indices.append(iter_cnt) -# `none_indices` now stores: [1, 3] +# `none_indices` 现在存储 [1, 3] ```
-**Takeaway**: +**经验**: -The built-in [enumerate](https://docs.python.org/3/library/functions.html#enumerate) function should be used (in conjunction with iterator unpacking) whenever it is necessary to track the iteration count of a for-loop. It is valuable to use this in conjunction with tuple unpacking. +内置的[enumerate](https://docs.python.org/3/library/functions.html#enumerate)函数应在任何需要记录for循环迭代位置的情况下(和可迭代物解包一起)使用。和元组解包一起使用会更加简化代码。
-**Reading Comprehension: enumerate** +**阅读理解:enumerate** -Use the iterable `"abcd"`, the `enumerate` function, and tuple-unpacking in a for-loop to create the list: `[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]` +在for循环中使用可迭代物 `"abcd"`,`enumerate` 函数,以及元组解包来创建以下列表:`[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]`
-**Reading Comprehension: Is it sorted?** +**阅读理解:是否顺序排列?** -Use control flow and looping tools to see if an iterable of numbers is sorted. +使用控制流和循环工具来检查某个成员为数字的可迭代物是否顺序排列。 -The variable `unsorted_index` should be initialized to `None`. If the iterable is *not* sorted, `unsorted_index` should store the index where the sequence *first* fell out of order. If the iterable is sorted, then `unsorted_index` should remain `None` and your code should print "sorted!". +将变量 `unsorted_index` 初始化为 `None`。如果可迭代物*不*顺序,那 `unsorted_index` 应该存储序列*第一个*不符合顺序的成员的索引。如果可迭代物顺序排列,那 `unsorted_index` 应该在最后依然为 `None`,且你的代码应该打印 "sorted!"。 -For instance: +比如说: - - given the iterable `my_list = [0, 1, -10, 2]`, `unsorted_index` should take the value `2`. - - given the iterable `my_list = [-1, 0, 3, 6]`, `unsorted_index` should be `None` and your code should print "sorted!". + - 设可迭代物 `my_list = [0, 1, -10, 2]`,`unsorted_index` 应该为 `2`。 + - 设可迭代物 `my_list = [-1, 0, 3, 6]`,`unsorted_index` 应该为 `None`,且你的代码应该打印 "sorted!"。
-## Links to Official Documentation +## 官方说明文档链接 -- [Iterable Definition](https://docs.python.org/3/glossary.html#term-iterable) -- [Functions on iterables](https://docs.python.org/3/howto/functional.html#built-in-functions) -- [enumerate](https://docs.python.org/3/library/functions.html#enumerate) +- [可迭代物定义](https://docs.python.org/3/glossary.html#term-iterable) +- [操作可迭代物的函数](https://docs.python.org/3/howto/functional.html#built-in-functions) +- [枚举](https://docs.python.org/3/library/functions.html#enumerate) -## Reading Comprehension Exercise Solutions: -**enumerate: Solution** +## 阅读理解答案 +**enumerate:解** ```python out = [] @@ -253,7 +252,7 @@ for num, letter in enumerate("abcd"): out.append((num, letter)) ``` -**Is it sorted?: Solution** +**是否顺序排列?:解** ```python my_list = [0, 1, -10, 2] unsorted_index = None diff --git a/Python/Module2_EssentialsOfPython/Itertools.md b/Python/Module2_EssentialsOfPython/Itertools.md index 3b6ec9e..aa33630 100644 --- a/Python/Module2_EssentialsOfPython/Itertools.md +++ b/Python/Module2_EssentialsOfPython/Itertools.md @@ -4,38 +4,38 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: simple use cases of python itertools, Difficulty: Easy, Category: Tutorial :keywords: itertools, examples, zip, range, enumerate, chain, combinations -``` + -# Python's "Itertools" -Python has an [itertools module](https://docs.python.org/3/library/itertools.html), which provides a core set of fast, memory-efficient tools for creating iterators. We will briefly showcase a few itertools here. The majority of these functions create [generators](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html), thus we will have to iterate over them in order to explicitly demonstrate their use. It is hard to overstate the utility of this module - it is strongly recommended that you take some time to see what it has in store. +# Python的“Itertools” +Python的[itertools模组](https://docs.python.org/3/library/itertools.html)提供了一套快速的高效使用内存的创建迭代器的核心工具。我会将在本节快速地展示一些itertool的工具。大部分这些函数都会创建[生成器](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html),因此我们将会需要迭代这些生成器才能展示它们的使用方法。此模组极其有用——本文强烈建议你花一些时间去了解该模组的内容。 -There are three built-in functions, `range`, `enumerate`, and `zip`, that belong in itertools, but they are so useful that they are made accessible immediately and do not need to be imported. It is essential that `range`, `enumerate`, and `zip` become tools that you are comfortable using. +Python有三个属于itertools的内置函数 `range`,`enumerate`,`zip`,但因为它们极其有用,所以Python允许你在不导入它们的情况下直接就可以使用这些函数。熟练使用 `range`,`enumerate`,和 `zip` 是很重要的技能。 **range** -Generate a sequence of integers in the specified "range": +生成包含描述的“界限”(range)中的整数列表: ```python -# will generate 0.. 1.. 2.. ... 8.. 9 +# 将会生成 0.. 1.. 2.. ... 8.. 9 >>> range(10) range(0, 10) >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -# will generate 0.. 3.. 6.. 9 +# 将会生成 0.. 3.. 6.. 9 >>> range(0, 10, 3) range(0, 10, 3) @@ -45,9 +45,9 @@ range(0, 10, 3) **enumerate** -Enumerates the items in an iterable: yielding a tuple containing the iteration count (starting with 0) and the corresponding item from the the iterable. +枚举可迭代物中的对象:每轮迭代提供一元组,其内容为迭代轮数(从0开始)以及对应的可迭代物成员。 ```python -# will generate (0, 'apple').. (1, 'banana').. (2, 'cat').. (3, 'dog')] +# 将会生成 (0, 'apple').. (1, 'banana').. (2, 'cat').. (3, 'dog')] >>> enumerate(["apple", "banana", "cat", "dog"]) @@ -57,13 +57,13 @@ Enumerates the items in an iterable: yielding a tuple containing the iteration c **zip** -Zips together the corresponding elements of several iterables into tuples. This is valuable for "pairing" corresponding items across multiple iterables. +将多个可迭代物的对应成员拉链(zip)到元组中。这为凑对多个可迭代物中对象很有用。 ```python >>> names = ["Angie", "Brian", "Cassie", "David"] >>> exam_1_scores = [90, 82, 79, 87] >>> exam_2_scores = [95, 84, 72, 91] -# will generate ('Angie', 90, 95).. ('Brian', 82, 84).. ('Cassie', 79, 72).. ('David', 87, 91)] +# 将会生成 ('Angie', 90, 95).. ('Brian', 82, 84).. ('Cassie', 79, 72).. ('David', 87, 91)] >>> zip(names, exam_1_scores, exam_2_scores) @@ -71,11 +71,11 @@ Zips together the corresponding elements of several iterables into tuples. This [('Angie', 90, 95), ('Brian', 82, 84), ('Cassie', 79, 72), ('David', 87, 91)] ``` *** -The following are some of the many useful tools provided by the `itertools` module: +以下是一些 `itertools` 模组中有用的函数: **itertools.chain** -Chains together multiple iterables, end-to-end, forming a single iterable: +将多个可迭代物背靠背连接在一起,返回单个可迭代物: ```python >>> from itertools import chain >>> gen_1 = range(0, 5, 2) # 0.. 2.. 4 @@ -83,41 +83,41 @@ Chains together multiple iterables, end-to-end, forming a single iterable: >>> iter_3 = ["moo", "cow"] >>> iter_4 = "him" -# will generate: 0.. 2.. 4.. 9.. 16.. 25.. 'moo'.. 'cow'.. 'h'.. 'i'.. 'm' +# 将会生成:0.. 2.. 4.. 9.. 16.. 25.. 'moo'.. 'cow'.. 'h'.. 'i'.. 'm' >>> chain(gen_1, gen_2, iter_3, iter_4) ``` **itertools.combinations** -Generate all length-n tuples storing "combinations" of items from an iterable: +生成所有长度为n的可迭代物成员“组合”: ```python >>> from itertools import combinations -# will generate: (0, 1, 2).. (0, 1, 3).. (0, 2, 3).. (1, 2, 3) ->>> combinations([0, 1, 2, 3], 3) # generate all length-3 combinations from [0, 1, 2, 3] +# 将会生成:(0, 1, 2).. (0, 1, 3).. (0, 2, 3).. (1, 2, 3) +>>> combinations([0, 1, 2, 3], 3) # 从 [0, 1, 2, 3] 的数字生成所有长度为3的组合 ```
-**Reading Comprehension: Itertools I** +**阅读理解:Itertools第一部分** -Using the `itertools.combinations` function, find the probability that two randomly drawn items from the list `["apples", "bananas", "pears", "pears", "oranges"]` would yield a combination of "apples" and "pears". +使用 `itertools.combinations` 函数来找出从列表 `["apples", "bananas", "pears", "pears", "oranges"]` 随机选择两个成员会提供“apples”和“pears”组合的几率。
-**Reading Comprehension: Itertools II** +**阅读理解:Itertools第二部分** -Given the list `x_vals = [0.1, 0.3, 0.6, 0.9]`, create a generator, `y_gen`, that will generate the y-value $y = x^2$ for each value of $x$. Then, using `zip`, create a list of the $(x, y)$ pairs, each pair stored in a tuple. +设列表 `x_vals = [0.1, 0.3, 0.6, 0.9]`,创建一个生成器 `y_gen` 来生成 $y = x^2$ 在每一个 $x$ 对应的的y值。然后,使用 `zip` 来创建一个包含 $(x, y)$ 元组的列表。
-## Links to Official Documentation +## 官方说明文档链接 - [range](https://docs.python.org/3/library/stdtypes.html#typesseq-range) - [enumerate](https://docs.python.org/3/library/functions.html#enumerate) @@ -125,9 +125,9 @@ Given the list `x_vals = [0.1, 0.3, 0.6, 0.9]`, create a generator, `y_gen`, tha - [itertools](https://docs.python.org/3/library/itertools.html) -## Reading Comprehension: Solutions +## 阅读理解答案 -**Itertools I: Solution** +**Itertools第一部分:解** ```python >>> from itertools import combinations @@ -140,7 +140,7 @@ Given the list `x_vals = [0.1, 0.3, 0.6, 0.9]`, create a generator, `y_gen`, tha -**Itertools II: Solution** +**Itertools第二部分:解** ```python >>> x_vals = [0.1, 0.3, 0.6, 0.9] @@ -149,7 +149,7 @@ Given the list `x_vals = [0.1, 0.3, 0.6, 0.9]`, create a generator, `y_gen`, tha [(0.1, 0.01), (0.3, 0.09), (0.6, 0.36), (0.9, 0.81)] ``` -In this instance, the use of `zip` is a bit contrived. We could have foregone creating `y_gen` by just using the following list-comprehension: +在这个情况下,使用 `zip` 其实有点没必要的复杂化了。我们完全可以跳过创建 `y_gen` 并使用列表理解: ```python >>> x_vals = [0.1, 0.3, 0.6, 0.9] >>> [(x, x**2) for x in x_vals] diff --git a/Python/Module2_EssentialsOfPython/Problems/DifferenceFanout.md b/Python/Module2_EssentialsOfPython/Problems/DifferenceFanout.md index e56ab94..3828bf3 100644 --- a/Python/Module2_EssentialsOfPython/Problems/DifferenceFanout.md +++ b/Python/Module2_EssentialsOfPython/Problems/DifferenceFanout.md @@ -4,94 +4,90 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: For-Loop Exercise, Difficulty: Easy, Category: Practice Problem :keywords: for loops, list, function, list comprehension, practice problem -``` + -# Difference Fanout +# 扇出差 -Given a list of numbers, for each number generate a list of the differences between it and $n_{fanout}$ (known as the **fanout** value) following numbers in the list. Return a list of all the lists generated for each number. For members in the list that have fewer than $n_{fanout}$ following members, calculate as many differences as possible. For example, suppose we want to compute the difference fanout on the list `[3, 2, 4, 6, 1]` with a fanout value of 3. Then we would compute: +设一列表的数字,为每个数字生成它与它在列表后 $n_{fanout}$(叫做**扇出**(fanout)值)个数字之间的差的列表。返回一个列表,其成员为为每一个数字生成的列表(也就是说返回的是成员为列表的列表)。如果列表成员之后的成员数小于 $n_{fanout}$,计算尽可能多的差。比如说,假设我们想要计算列表 `[3, 2, 4, 6, 1]` 的扇出差,且扇出值为3,那我们应该计算: - $3 \rightarrow [2 - 3, 4 - 3, 6 - 3]$ - $2 \rightarrow [4 - 2, 6 - 2, 1 - 2]$ - $4 \rightarrow [6 - 4, 1 - 4]$ - $6 \rightarrow [1 - 6]$ - $1 \rightarrow []$ - + ``` Python -# example behavior +# 范例行为 >>> difference_fanout([3, 2, 4, 6, 1], 3) [[-1, 1, 3], [2, 4, -1], [2, -3], [-5], []] ``` -You will want to know about [lists](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Lists), [indexing & slicing](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Introducing-Indexing-and-Slicing) lists, and [for-loops](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ForLoops.html) to solve this problem. +你会想要先阅读本文对[列表](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#列表),[索引和切片](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#索引和切片简介)列表,以及[for循环](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/For循环.html)的讨论,然后再解决本问题。 -For extra credits (and some extra fun!), try to write your function only using [list comprehension](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#List-&-Tuple-Comprehensions). - -## Solution: difference_fanout using for-loops -We will naturally tackle this problem by performing nested for-loops. The outermost for-loop will loop over each number in the list. We will refer to this number as the "base number". We will want the inner for-loop to iterate ahead of the base number so that we can compute the differences between it and its $n_{fanout}$ neighbors. We will need to take care re-initialize our intermediate list of differences for each new base number, otherwise each subtraction will get appended to one long list. +如果想要获得额外分(以及额外的乐趣!)的话,尝试仅仅使用[列表理解](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#列表和元组理解)来编写你的函数。 +## 解:使用for循环计算扇出差 +我们将会使用最直接了当的嵌套for循环来解决本问题。外层for循环会迭代列表中的每一个数字。我们这个数字将其称为“基础数”(base number)。我们将想要内层for循环迭代基础数之后的数字,这样我们可以计算基础数和它 $n_{fanout}$ 个邻居们的差。我们将会为每一个基础数重新初始化中间的列表,不然每个差都会被附加到一个很长的列表后。 ```python def difference_fanout(l, fanout): - """ Return a list of differences for - each value with its following terms - + """ 返回列表,其成员为值和它后面成员之间的差 + Parameters ---------- l: List[Number] - Input list of base numbers. - + 作为输入的基础数列表 + fanout: int - Number of neighbors to compute differences against. - + 和多少个邻居计算差 + Returns ------- List[List[Number]] """ - all_fanouts = [] # will store each list of fanouts + all_fanouts = [] # 会储存每一个扇出差的列表 for i, base_number in enumerate(l): - # `base_fanout` will store the differences between - # the base number's successive neighbors and base number + # `base_fanout` 会储存基础数和它之后邻居的差 base_fanout = [] for neighbor in l[i+1: i+1+fanout]: base_fanout.append(neighbor - base_number) - + all_fanouts.append(base_fanout) return all_fanouts ``` -Note our use of [enumerate](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#Enumerating-iterables); this permits us to simultaneously access our base number, which we use in the subtraction, as well as its index-position within the list `l`, which we use to determine the neighbors. +请注意我们使用了[enumerate](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#枚举可迭代物);这允许我们同时访问我们的基础数(来求差)以及它在列表 `l` 中的索引(来确定它的邻居是哪些)。 -Next, you may be concerned that our inner-loop will attempt to iterate beyond the end of the list. Consider the case in which `base_number` is the final element in `l`, thus `l[i+1: i+1+fanout]` would be equivalent to `l[len(l): len(l)+fanout]` - the stopping point for this slice clearly reaches beyond the extent of `l` (assuming `fanout > 0`). Fortunately, this is not an oversight on our part. While indexing a list outside of its bounds will raise an error, recall that [a slice will automatically limit itself to be within bounds of a given sequence](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Handling-out-of-bounds-indices). That is, `l[i+1: i+1+fanout]` actually behaves like `l[min(i, len(l)-1): min(len(l), i+1+fanout)]` (assuming we are dealing only with positive indices and non-empty lists). Thus our inner-loop will naturally limit itself. In the case that `base_number` is the final element in `l`, the inner-loop will exit immediately, leaving `base_fanout` empty. Although somewhat obscure, this is an important aspect of Python's slicing mechanism to keep in mind. +你可能会担心我们的内循环会试图迭代列表结尾之后的数字。考虑 `base_number` 为 `l` 的最后成员的情况。那么 `l[i+1: i+1+fanout]` 等值于 `l[len(l): len(l)+fanout]`——这个切片的结尾索引明显超过了 `l` 的长度(假设 `fanout > 0`)。幸运的是,这并不是我们的疏忽。虽然索引列表范围外的成员会导致错误,但是请回忆:[切片会自动将其限制在序列的边界之中](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#处理超界索引)。也就是说,`l[i+1: i+1+fanout]` 其实行为和 `l[min(i, len(l)-1): min(len(l), i+1+fanout)]` 一样(假设我们仅仅在处理正索引和非空的列表)。因此我们的内循环会自然地限制自身。在 `base_number` 为 `l` 最后成员的情况下,内循环会立刻退出,使得 `base_fanout` 为空。虽然有一点费解,但是这是一个值得记忆的Python切片特征。 -## Solution: difference_fanout using list comprehensions -We can make judicious use of nested [list comprehensions](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#List-&-Tuple-Comprehensions) to simplify our solution. Although the syntax may appear to be convoluted at first glance, it permits us proceed without worrying about initializing multiple empty lists and appending to them at the right points in our nested for-loops +## 解:使用列表理解计算扇出差 +我们可以审慎地嵌套[列表理解](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#列表和元组理解)来简化我们的答案。虽然这语法可能第一眼看上去有一点复杂,但是它允许我们不用担心初始化多个列表并在嵌套for循环中正确的地方向它们附加内容。 ``` Python def difference_fanout(l, fanout): - """ Return a list of differences for - each value with its following terms - + """ 返回列表,其成员为值和它后面成员之间的差 + Parameters ---------- l: List[Number] - Input list - + 作为输入的基础数列表 + fanout: int - Number of neighbors to compute difference with - + 和多少个邻居计算差 + Returns ------- List[Number] @@ -100,32 +96,30 @@ def difference_fanout(l, fanout): for i,base in enumerate(l)] ``` -See that the outermost list comprehension loops over the base number, as did the outer for-loop in the prior solution, and that the innermost list comprehension plays the same roll as the inner for-loop. +注意最外层的列表理解迭代了基础数,如上一个答案的外层for循环一般,而里层的列表理解达成了和上一个答案的里层for循环一样的目的。 -There are fewer potential points of failure in this solution, as its conciseness removes the "moving parts" that had to be managed in the previous solution. This should help demonstrate the power of the comprehension expression syntax. +在这个版本的解中可能导致错误的地方比前一个答案少,因为其简短性使得你不需要担心之前答案需要处理的“中间部分”。这应该演示了理解表达式语法的强大。 -## Extension -Recall from [earlier](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#Functions-are-Objects) that functions are, under the hood, just objects with some special operations that allow you to "call" a function. This means that you can pass other functions as parameters into a function. It is especially powerful, since it enables us to generalize the purposes of our functions. For example, we don't have to limit our function to just computing the **difference** between members and their following terms; we can apply **any** *binary operation*. Instead of finding the difference, we can calculate the sum or product or even concatenate two strings for a list of string. The possibilities are limitless. +## 扩展 +回忆[前文](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#函数也是对象),函数其实就是提供了“调用函数”这个特殊功能的对象。这意味着你可以将函数作为参数输入到别的函数中。这一点极其强大,因为这将允许我们扩大我们函数的运用场合。比如说,我们不需要限制我们的函数来仅仅计算成员和之后项目的**差**;我们可以使用**任何***二元运算*。与其计算差,我们可以计算和或乘积或甚至在字符串列表的情况下粘连字符串。可能性无限;有限的仅仅是你的想象力。 -Armed with this knowledge, we can generalize the code. +在了解了这一点后,我们可以归纳我们的代码。 ```Python def apply_fanout(l, fanout, op): - """ Return a list of outputs for each value - after applying a binary operation between - the value and its following terms - + """ 返回一个列表,成员为值和在它后面成员之间 + 进行二元运算的结果 + Parameters ---------- l: List[Any] - Input list - + 输入列表 + fanout: int - Number of neighbors to apply the operation with - + 和多少个邻居进行运算 + op: Callable[[Any, Any], Any] - Any binary operation to be applied to fanout-pairs - of elements in `l`. - + 任何用来对 `l` 中对象组成的扇出对操作的二元运算 + Returns ------- List[List[Any]] @@ -133,13 +127,13 @@ def apply_fanout(l, fanout, op): return [[op(neighbor, base) for neighbor in l[i+1:i+1+fanout]] for i,base in enumerate(l)] ``` -Now, we can rewrite `difference_fanout` simply as +现在,我们可以简单地重写 `difference_fanout` 为: ``` Python -def subtract(a, b): +def subtract(a, b): return a - b def difference_fanout(l, fanout): return apply_fanout(l, fanout, subtract) ``` -We can easily change `subtract` to some other function for a totally different use. +我们可以轻松地将 `subtract` 换成其它函数来达到完全不同的目的。 diff --git a/Python/Module2_EssentialsOfPython/Problems/EncodeAsString.md b/Python/Module2_EssentialsOfPython/Problems/EncodeAsString.md index 19af2c4..9a760e5 100644 --- a/Python/Module2_EssentialsOfPython/Problems/EncodeAsString.md +++ b/Python/Module2_EssentialsOfPython/Problems/EncodeAsString.md @@ -4,52 +4,51 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: String Encoding Exercise, Difficulty: Medium, Category: Practice Problem :keywords: function, string, casting, practice problem -``` + -# Encode as String -Sometimes it is very important to handle different input object types differently in a function. This problem will exercise your understanding of types, control-flow, dictionaries, and more. +# 编码为字符串 +有时,我们需要在函数中根据输入类型的不同进行不同的操作。本题将考察你对类型,控制流,词典,和更多概念的掌握。 ->We want to encode a sequence of Python objects as a single string. The following describes the encoding method that we want to use for each type of object. Each object's transcription in should be separated by `" | "`, and the result should be one large string. +>我们想要将一序列的Python对象编码为一个字符串。以下描述了对每种对象类型的编码规则。每个对象的翻译结果应由 `" | "` 隔开,并在最后函数应返回一个长字符串。 + +- 如果对象是整数,通过拼写它在10进制下每一位数字将其转化为字符串,如下: +`142` $\rightarrow$ `one-four-two`;`-12` $\rightarrow$ `neg-one-two`。 +/ 如果对象是浮点数,通过相同的规则转化其整数部分(通过取整得到)并在后面添加字符串`"and float"`: +`12.324` $\rightarrow$ `one-two and float`。 +- 如果对象是字符串,直接附加不需要额外操作。 +- 如果对象是任何其它类,附加`''`。 -- If the object is an integer, convert it into a string by spelling out each digit in base-10 in this format: -`142` $\rightarrow$ `one-four-two`; `-12` $\rightarrow$ `neg-one-two`. -- If the object is a float, just append its integer part (obtained by rounding down) the same way and the string `"and float"`: -`12.324` $\rightarrow$ `one-two and float`. -- If the object is a string, keep it as is. -- If the object is of any other type, return `''`. - ``` Python -# example behavior +# 范例行为 >>> s = concat_to_str([12,-14.23,"hello", True, ... "Aha", 10.1, None, 5]) >>> s 'one-two | neg-one-four and float | hello | | Aha | one-zero and float | | five' ``` -**Tips**: check out the `isinstance` function introduced [here](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html) for handling different types. Also, consider creating a helper function for the conversion from integer to our special-format string, since we have to do it twice. It's always good to extrapolate repeated tasks into functions. You'll also need to hard-code the conversion from each digit to its English spell-out. - +**提示**:查阅在[这里](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html)介绍的 `isinstance` 函数来处理不同的数据类型。同时,你可以考虑创建一个辅助函数来将整数编码到我们特殊格式的字符串,因为我们在处理整数和浮点数时都要用到它。在任何情况下,将重复进行的工作抽取为函数都是一个好习惯。你将会需要硬编码(hardcode)每个数字到它英文名字的转化表。 -## Solution -Our solution is broken down into three simple functions. `int_to_str` is used to map signed integers to English words. `item_to_transcript` is capable of mapping an object of any type to its string representation, in accordance with the prescription made by the problem statement. Finally, `concat_to_str` orchestrates these two helper functions, looping over each object in our input list, mapping each object to its string representation, and joining these strings with `' | '`. +## 解 +我们的解总分化为三个简单的函数。`int_to_str` 用来将整数转化成英语单词。`item_to_transcript` 将任何类型的对象转化为根据本题描述的字符串格式。最后,`concat_to_str` 迭代输入列表,调用另外两个辅助函数,将每个对象转化为字符串表达方法,并由 `' | '` 链接这些字符串。 ```python def int_to_str(n): - """ - Takes an integer and formats it into a special string + """ + 接受一个整数并将其格式化为字符串: e.g. 142 -> "one-four-two" -12 -> "neg-one-two" """ @@ -57,7 +56,7 @@ def int_to_str(n): "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "-": "neg"} return "-".join(mapping[digit] for digit in str(n)) - + def item_to_transcript(item): """ Any -> str """ if isinstance(item, bool): return '' @@ -67,14 +66,13 @@ def item_to_transcript(item): return '' def concat_to_str(l): - """ - Maps a list of objects to their string - representations concatenated together. + """ + 将一列表的对象转化成字符串表达方式并粘连在一起 Parameters ---------- l: List[Any] - Input list of objects + 输入对象的列表 Returns ------- @@ -88,22 +86,22 @@ def concat_to_str(l): return " | ".join(item_to_transcript(item) for item in l) ``` -We use the `str.join` function along with a generator comprehensions in a couple places in our solution. Recall that +我们在本答案中多次使用 `str.join` 函数和生成器理解。请回忆: ```python "".join(x for x in some_iterable_of_strings) ``` -is equivalent to the long-form code: +等值于以下更长的代码: ```python out = "" for x in some_iterable_of_strings: out += "" + x -``` +``` -`int_to_str` plays a clever trick to convert each integer, digit-by-digit, into its string form - it calls `str` on the integer. This converts the integer into a string, which is a [sequence](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html). This permits us to access each digit of the integer and even iterate over them: +`int_to_str` 为了将整数的每位数转化成字符串使用了一个小技巧——它用 `str` 将整数转化为字符串。而字符串是一个[序列](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html)。这允许我们访问整数的每一位数,甚至迭代它们: ```python -# casting an integer to a string makes its -# sign and digits accessible via indexing/iteration +# 将整数转化为字符串让我们可以通过索引/迭代来 +# 访问它的符号和位数 >>> x = str(-123) >>> x '-123' @@ -112,9 +110,9 @@ for x in some_iterable_of_strings: >>> x[-1] '3' ``` -Thus, in total `"-".join(mapping[digit] for digit in str(n))` is responsible for casting an integer to a string, iterating over each of its digits and mapping them to their corresponding word using the [dictionary](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html) that we defined in the function. +因此,`"-".join(mapping[digit] for digit in str(n))` 将整数转化为字符串,迭代其每一位数,并使用函数中定义的[词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html)来将其转换成对应的单词。 -`item_to_transcript` it an especially slick function. First, let's make clear the fancy use of the inline syntax here. This function: +`item_to_transcript` 是一个特别骚操作的函数。首先,它并不使用elif语句,但这: ```python def item_to_transcript(item): """ Any -> str """ @@ -124,7 +122,7 @@ def item_to_transcript(item): if isinstance(item, str): return item return '' ``` -is entirely equivalent to this function: +和以下完全等值: ```python def item_to_transcript_alt(item): """ Any -> str """ @@ -139,20 +137,20 @@ def item_to_transcript_alt(item): else: return '' ``` -The latter uses the familiar pattern of [if-elif-else](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html) statements and makes for a completely satisfactory version of the function. See, however, that each of the [multiple return statements](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#Multiple-return-Statements) in `item_to_transcript` guarantees the same logic, in that if a condition is meant a value will be returned by the function and none of its subsequent code can be visited. That is, if `item` is an integer the second if-condition will evaluate to `True` and `int_to_str(item)` will be returned, immediately expelling the point of execution from the body of the function. +后者使用了熟悉的[if-elif-else](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html)语句,且为一个完全合理可接受的版本。但请注意在 `item_to_transcript` 中的[多个返回语句](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#Multiple-return-Statements)实现了一样的逻辑。也就是说如果某个条件被满足,它对应的值会被返回,且后面的任何代码都会被跳过。比如说,如果 `item` 是一个整数,那么第二个if条件会运算为真并返回 `int_to_str(item)`,同时,程序立即从函数主体跳出。 -Ultimately, the preference of one function over the other is merely a matter of stylistic preference. You also have likely noted the peculiar in-line `if-return` expressions. These too are only stylistic choices; +在两个函数中选哪个“更好”终归是一个风格上的偏好。你可能注意到了单行的 `if-return` 表达式。这也仅仅是一个风格的选择。这: ```python if isinstance(item, int): return int_to_str(item) ``` -is no different from +和以下没有区别: ```python if isinstance(item, int): return int_to_str(item) ``` -The use of in-line `if-return` expressions in `item_to_transcript` does a nice job emphasizing the dictionary-like mapping behavior of the function: the form of the code suits its functionality nicely. That being said, these should generally be used sparingly. Some may call this a "cute" trick. And it is. This code is cute. I write cute code. +在 `item_to_transcript` 中使用单行的 `if-return` 表达式强调了该函数像词典一般的行为:代码的格式很好地对应了其功能。但就算如此,这样的单行语句也要谨慎使用。有些人可能认为这是一个可爱的小技巧。我也觉得它很可爱。这代码很可爱。我写的代码很可爱。 -Finally, you may have noticed what looks like a redundancy in our code: our first `if` statement returns `''` if `item` is `True` or `False`, and our final line of code returns `''` if none of the preceding conditions were met (i.e. `item` is not a `bool`, `int`, `float`, or `str` type object). Why then did we not just merge our first `if` clause with this ultimate catch-all? The reason is that `True` and `False` are not only instances of the boolean type, they are also integers! `True` behaves like the integer `1` and `False` like `0`: +最后,你可能在代码中注意到一个像是重复的部分:我们的第一个 `if` 语句当 `item` 为 `True` 或 `False`(布尔值)时返回 `''`,而我们的最后一行代码在以上所有情况都没有满足时(也就是当 `item` 不是 `bool`,`int`,`float`,或 `str` 类型对象时)会返回 `''`。为什么我们不将最后一行和第一个 `if` 句段合并呢?不这样做的原因是 `True` 和 `False` 不仅仅是布尔类型的实例,它们也是整数!`True` 的行为类似于整数 `1` 而 `False` 像 `0`: ```python >>> isinstance(True, int) and isinstance(True, bool) @@ -162,5 +160,5 @@ True 4 ``` -Thus, had we not taken care to check for booleans up front, `True` and `False` would have been mapped to `'one'` and `'zero'`, respectively, rather than `''`. This is a relatively subtle edge case to catch. +因此,如果我们没有首先检查布尔值,`True` 和 `False` 会被分别转化成 `'one'` 和 `'zero'`,而不是 `''`。这是一个比较微妙难抓的边界情况。 diff --git a/Python/Module2_EssentialsOfPython/Problems/MarginPercentage.md b/Python/Module2_EssentialsOfPython/Problems/MarginPercentage.md index d8b24c8..060970e 100644 --- a/Python/Module2_EssentialsOfPython/Problems/MarginPercentage.md +++ b/Python/Module2_EssentialsOfPython/Problems/MarginPercentage.md @@ -4,104 +4,103 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Within Margin Exercise, Difficulty: Medium, Category: Practice Problem :keywords: function, control flow, comparisons, practice problem -``` + -# Within Margin Percentage +# 错误范围内百分比 ->An algorithm is required to test out what percentage of the parts that a factory is producing fall within a safety margin of the design specifications. Given a list of values recording the metrics of the manufactured parts, a list of values representing the desired metrics required by the design, and a margin of error allowed by the design, compute what fraction of the values are within the safety margin (`<=`) +>我们需要设计一个算法来测试某工厂制造的零件有多少百分比属于设计规格的可接受范围内。函数接受一列表的零件度量,一列表的设计规格的理想度量,以及一个可以接受的错误范围,并返回有多少部分的零件属于安全范围内(`<=`)。 ``` Python -# example behavior +# 范例行为 >>> within_margin_percentage(desired=[10.0, 5.0, 8.0, 3.0, 2.0], ... actual= [10.3, 5.2, 8.4, 3.0, 1.2], ... margin=0.5) 0.8 ``` -See that $4/5$ of the values fall within the margin of error: $1.2$ deviates from $2$ by more than $0.5$. +注意 $4/5$ 的值都处于错误范围内:$1.2$ 离 $2$ 差的超过 $0.5$。 -Complete the following function; consider the edge case where `desired` and `actual` are empty lists. +完成以下的函数;请考虑 `desired` 和 `actual` 是空列表的边缘情况。 ```python def within_margin_percentage(desired, actual, margin): - """ Compute the percentage of values that fall within - a margin of error of the desired values - + """ 计算多少部分的值属于期望值的错误范围内 + Parameters ---------- desired: List[float] - The desired metrics - + 期望值 + actual: List[float] - The corresponding actual metrics. - Assume `len(actual) == len(desired)` - + 对应的实际值 + 假设 `len(actual) == len(desired)` + margin: float - The allowed margin of error - + 可接受的错误范围 + Returns ------- float - The fraction of values where |actual - desired| <= margin + 多少部分的值满足 |actual - desired| <= margin """ - # YOUR CODE HERE + # 你的代码 pass ``` -You will want to be familiar with [comparison operators](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#Comparison-Operations), [control flow](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html), and [indexing lists](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Introducing-Indexing-and-Slicing) lists to solve this problem. +你会需要熟悉[对比操作符](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#比较运算),[控制流](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html),和[列表索引](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#索引和切片简介)来解决本问题。 -## Solution -This problem can solved by simply looping over the pairs of actual and desired values and tallying the pairs that fall within the margin: +## 解 +本题可以通过简单地循环实际和可接受值并计算其中多少属于安全范围内来解决: ``` Python def within_margin_percentage(desired, actual, margin): - """ Compute the percentage of values that fall within - a margin of error of the desired values - + """ 计算多少部分的值属于期望值的错误范围内 + Parameters ---------- desired: List[float] - The desired metrics - + 期望值 + actual: List[float] - The actual metrics - + 对应的实际值 + 假设 `len(actual) == len(desired)` + margin: float - The allowed margin of error - + 可接受的错误范围 + Returns ------- float - The fraction of values where |actual - desired| <= margin + 多少部分的值满足 |actual - desired| <= margin """ - count = 0 # tally of how values are within margin + count = 0 # 计算多少值属于范围内 total = len(desired) for i in range(total): if abs(desired[i] - actual[i]) <= margin: - count += 1 # Equivalent to `count = count + 1` + count += 1 # 等值于 `count = count + 1` return count / total if total > 0 else 1.0 ``` -See that we handle the edge case where `desired` and `actual` are empty lists: the [inline if-else statement](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#Inline-if-else-statements) `count / total if total > 0 else 1` will return `1` when `total` is 0: +注意我们处理了 `desired` 和 `actual` 是空列表的边缘情况:[单行if-else语法](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#单行的if-else语句) `count / total if total > 0 else 1` 将在 `total` 为0时返回1: ```python >>> within_margin_percentage([], [], margin=0.5) 1.0 ``` -which is arguably the appropriate behavior for this scenario (no values fall outside of the margin). Had we not anticipated this edge case, `within_margin_percentage([], [], margin=0.5)` would raise `ZeroDivisionError`. +以上行为应该是这种情况下的正确行为(因为没有任何值在安全范围外面)。如果我们没有处理这个边缘情况,`within_margin_percentage([], [], margin=0.5)` 会导致 `ZeroDivisionError`。 -It is also possible to write this solution using the built-in `sum` function and a [generator comprehension](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#Creating-your-own-generator:-generator-comprehensions) that filters out those pairs of items that fall outside of the desired margin: +你也可能会使用内置的 `sum` 函数和[生成器理解](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#创建你自己的生成器:生成器理解)来过滤在安全范围外的成员对: ```python def within_margin_percentage(desired, actual, margin): @@ -110,5 +109,5 @@ def within_margin_percentage(desired, actual, margin): return count / total if total > 0 else 1.0 ``` -It is debatable whether this refactored solution is superior to the original one - it depends largely on how comfortable you, and anyone else who will be reading your code, are with the generator comprehension syntax. +后者是否强于前者是有待商榷——这取决于你和任何其它会阅读你的代码的人有多熟悉生成器理解语法。 diff --git a/Python/Module2_EssentialsOfPython/Problems/MergeMaxDicts.md b/Python/Module2_EssentialsOfPython/Problems/MergeMaxDicts.md index 43ebbbb..abdc8d1 100644 --- a/Python/Module2_EssentialsOfPython/Problems/MergeMaxDicts.md +++ b/Python/Module2_EssentialsOfPython/Problems/MergeMaxDicts.md @@ -4,103 +4,101 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Dictionary Merge Exercise, Difficulty: Easy, Category: Practice Problem :keywords: dictionary, merge, practice problem -``` + -# Merging Two Dictionaries -> Merge two [dictionaries](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#Data-Structures-(Part-II):-Dictionaries) together such that the resulting dictionary always retain the *greater* value among mappings with common keys. +# 合并两个词典 +> 合并两个[词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#数据结构(第二部分):词典),在词典有着共同的键时使用*更大*的对应值。 -Here's an example: +以下为一个例子: ```python -# merging two dictionaries, retaining the greatest value among -# common keys +# 合并两个词典,在遇到共同的键时优先使用更大值 >>> dict1 = {'bananas': 7, 'apples': 3, 'pears': 14} >>> dict2 = {'bananas': 3, 'apples': 6, 'grapes': 9} >>> merge_max_mappings(dict1, dict2) {'bananas': 7, 'apples': 6, 'pears': 14, 'grapes': 9} ``` -Write a function that accepts two dictionaries and merges them in the fashion shown above. The [dictionaries' keys need not be strings](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#What-Can-a-Dictionary-Store?), and the values should be any data type that can be ordered (e.g. can be compared using the inequality operators `<`, `>`, etc.). +编写一个接受两个词典并如上合并它们的函数。[词典的键不一定是字符串](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#词典可以储存什么?),且它们的值应该是任何可以被排序的数据类型(也就是说可以被不等操作符 `<`,`>` 等对比)。 -## A Simple, Buggy Solution -Let's begin by writing a straightforward but flawed solution to our problem. The following function will correctly merge its two input dictionaries and is generally well-written, however, something insidious is afoot... Can you identify the bad behavior that will result from this function? +## 简单而有错的解 +让我们首先编写一个直接但实际上有错误的解。以下函数将会正确地合并两个输入词典且总体而言写得挺好的,但是在其中潜伏着邪恶...你可以找出该函数可能的错误行为么? ```python def buggy_merge_max_mappings(dict1, dict2): - # create the output dictionary, which contains all - # the mappings from `dict1` + # 创建一个输出词典,其成员包含 `dict1` 的对应关系 merged = dict1 - - # populate `merged` with the mappings in dict2 if: - # - the key doesn't exist in `merged` - # - the value in dict2 is larger - for key in dict2: + + # 在以下情况之一满足时向 `merged` 添加 dict2 里的对应关系: + # - 键在 `merged` 中不存在 + # - dict2 的值更大 + for key in dict2: if key not in merged or dict2[key] > merged[key]: merged[key] = dict2[key] return merged ``` -Let's first see what this function does right. Recall that [iterating over a dictionary](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#Inspecting-a-Dictionary) will produce each of its keys one-by-one. Thus `for key in dict2` loops over every key in `dict2`. We then set a key-value from `dict2` mapping in `merged` if that key doesn't exist in merged or if the value is larger than the one stored in existing mapping. Given that `merged` is initialized to have the same mappings as `dict1`, this is a correct algorithm for merging our two dictionaries based on max-value. +让我们首先注意该函数做对的地方。回忆[迭代词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#检查词典)将会一个一个返回词典键的事实。因此,`for key in dict2` 会循环迭代 `dict2` 中所有的键。然后当 `dict2` 的键在 `merged` 中不存在或当 `dict2` 的值大于已经存储的值时,我们在 `merged` 中更新 `dict2` 的键值。因为 `merged` 初始化为 `dict1` 中的对应关系,这是一个正确的根据最大值合并两个词典的方法。 -The problem with our function is that we inadvertently merge `dict2` *into* `dict1`, rather than merging the two dictionaries into a *new* dictionary. Recall that dictionaries are [mutable](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Variables_and_Assignment.html#Referencing-a-Mutable-Object-with-Multiple-Variables) objects and that the statement `merged = dict1` simply assigns a variable that references `dict1` rather than creating a new copy of the dictionary. Thus calling this function will *mutate* (change) the state of `dict1`, as demonstrated here: +我们这个函数的问题在于我们将 `dict2` 合并*进*了 `dict1`,而不是将两个词典合并成一个*新*词典。词典是[可变](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Variables_and_Assignment.html#多个变量引用一个可变对象)对象,而 `merged = dict1` 语句仅仅赋值一个变量来引用 `dict1`,而不是创建该词典的新的复制品。因此调用该函数将会*改变* `dict1` 的内态,如下所见: ```python ->>> exam_1 = dict(Alice=99, Bob=87, Cindy=65) # equivalent to {'Alice': 99, 'Bob': 87, 'Cindy': 65} +>>> exam_1 = dict(Alice=99, Bob=87, Cindy=65) # 等值于 {'Alice': 99, 'Bob': 87, 'Cindy': 65} >>> exam_2 = dict(Alice=77, Bob=90, Cindy=78) >>> buggy_merge_max_mappings(exam_1, exam_2) {'Alice': 99, 'Bob': 90, 'Cindy': 78} ``` -See that the value of `exam_1` has changed, and that it matches the output of our function: +请注意 `exam_1` 的值也被改变了,且其和函数输出一样: ```python >>> exam_1 {'Alice': 99, 'Bob': 90, 'Cindy': 78} ``` -To reiterate, this is because the statement `merged = dict1` found at the beginning of our function *merely creates a reference to* `dict1`, not a copy of it. In the above example `exam_1` stored a class' exam-1 scores for each student. After passing it to our function, it now stores the max score for each student across two exams! +重申一遍,这是因为在我们函数开头的语句 `merged = dict1` *仅仅创建了一个引用*指向 `dict1`,而不是复制了它的值。在以上范例中 `exam_1` 储存了每个学生的第一轮考试成绩,而在输入到函数内后它现在储存了每个学生在两轮考试中的最大值! -While we are likely to have tested that our function properly merges dictionaries as we desire, we are less likely to test that it leaves its inputs unchanged. This is a valuable lesson to be l +虽然我们大概率会测试我们的函数是否返回了正确的合并词典,但我们很可能不会去测试它是否不会修改其输入参数。这是编写正确代码很重要的一课。
-**Takeaway** +**经验**: -- Be mindful of [object mutability](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Variables_and_Assignment.html#Mutable-&-Immutable-Types-of-Objects) and take care never to unwittingly mutate an input variable or global scope variable within a function. -- When testing a function, include a check that the function does not mutate its inputs. +- 注意[对象可变性](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Variables_and_Assignment.html#可变和不可变对象)并小心不要无意在函数中修改输入参数或全球域(global scope)变量。 +- 在测试函数时,包含一个检查函数是否修改输入的测试。
-## A Simple, Correct Solution +## 简单而正确的解 -We can easily stomp the bug in the previous function; updating `merged = dict1` with either `merged = dict(dict1)` or `merged = dict1.copy()` will ensure that `merged` references a *new* dictionary, which we are free to update: +我们可以很轻松地解决以上函数的错误;将 `merged = dict1` 修改为 `merged = dict(dict1)` 或 `merged = dict1.copy()` 将保证 `merged` 引用一个*新*词典。这样我们可以随意更新它: ```python def simple_merge_max_mappings(dict1, dict2): - """ Merges two dictionaries based on the largest value in a given mapping. + """ 根据对应关系中最大的值来合并两个词典。 Parameters ---------- dict1 : Dict[Any, Comparable] dict2 : Dict[Any, Comparable] - + Returns ------- Dict[Any, Comparable] - The merged dictionary + 合并的词典 """ merged = dict(dict1) for key in dict2: @@ -109,33 +107,33 @@ def simple_merge_max_mappings(dict1, dict2): return merged ``` -Note the use of simple and descriptive variables (e.g. we use the variable name `key` when we iterate over the keys of a dictionary). This, along with a good docstring, makes our code easy to read, understand, and debug. Also note that our code is general: it makes no presumptions about the dictionaries' keys - they need not be strings nor of any other particular type. Similarly, the only constraint on the dictionaries' values is that they can be compared against one another. This is reflected in the docstring of our function. +注意我们使用的变量名字的简单性和描述性(比如说我们在迭代词典键时使用了函数名 `key`)。这个习惯以及一个好的docstring会使得我们的代码很易读,易懂,和易纠错。同时注意,我们的代码是广义的:这个函数没有对词典的键进行任何假设——词典的键没必要一定是字符串或任何其它某种类型。相同的,函数对词典的值的唯一要求就是它们必须可以相互比较。我们函数的docstring反映了这一点。 -Consider the importance of the ordering of the conditional statement: +请注意我们条件语句顺序的重要性: ```python if key not in merged or dict2[key] > merged[key]: ``` -What is different if we flip the ordering of the terms? I.e.: +当我们将其中的项顺序反向会有什么区别? ```python if dict2[key] > merged[key] or key not in merged: ``` -The problem with this flipped ordering is that the given key may not exist in `merged` yet, thus `dict2[key] > merged[key]` will raise a `KeyError`. Using the original ordering, such a case would cause `key not in merged` to return `True`, and the overall expression will return `True` without evaluating the second part of the expression (convince yourself that `False or ` should will always return `False`). +这个反向顺序的问题在于当某个键不存在于 `merged` 中时,`dict2[key] > merged[key]` 会导致 `KeyError`。使用原本的顺序则会导致 `key not in merged` 计算为 `True`;这使得程序跳过会报错的条件语的后半部分并直接返回 `True`(向自己证明 `True or <随便什么>` 永远都会返回 `True`)。 -## A Minor Optimization +## 小改进 -Supposing that your code makes heavy use of dictionary merging and that its performance is a bottleneck for the overall performance of your code, then there is a minor optimization that we can implement. +如果你的代码大量使用词典合并,且其效率为整个程序的效率瓶颈,那么我们可以实现一个小改进。 -Consider a case of extreme imbalance in the sizes of our dictionaries; suppose `dict1` is contains one key while `dict2` contains 10,000. It would be preferable for our solution to manually iterate over the smaller of these two dictionaries. We can easily accommodate this in our function by choosing `merged` to be the longer of the two dictionaries and iterating over the other dictionary: +假设我们两个词典的大小差距很大:比如说 `dict1` 有一个键,而 `dict2` 有一万个键,那么迭代两个词典中更小的那个会让我们花得时间更少(具体原因可以思考一下;请回忆算法复杂度)。我们可以简单地实现这个小改进;只要将 `merged` 设为两个词典中更大的那个并迭代另外那个词典就行了: ```python def opt_merge_max_mappings(dict1, dict2): - """ Merges two dictionaries based on the largest value in a given mapping. + """ 根据对应关系中最大的值来合并两个词典。 Parameters ---------- @@ -145,25 +143,25 @@ def opt_merge_max_mappings(dict1, dict2): Returns ------- Dict[Any, Comparable] - The merged dictionary + 合并的词典 """ - # we will iterate over `other` to populate `merged` + # 我们将会迭代 `other` 来修改 `merged` merged, other = (dict1, dict2) if len(dict1) > len(dict2) else (dict2, dict1) merged = dict(merged) - + for key in other: if key not in merged or other[key] > merged[key]: merged[key] = other[key] return merged ``` -Here, we make keen use of a [inline if-else statement](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#Inline-if-else-statements) and [iterable unpacking](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#%E2%80%9CUnpacking%E2%80%9D-iterables), which helps keep our code succinct despite the logic that we have added to it. See that +在这里,我们通过使用[单行if-else语句](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html#单行的if-else语句)和[可迭代物解包](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html#“解包”可迭代物)来在增加额外逻辑的同时不让代码太过复杂。这行代码: ```python merged, other = (dict1, dict2) if len(dict1) > len(dict2) else (dict2, dict1) ``` -is equivalent to: +和以下等值: ```python if len(dict1) < len(dict2): merged = dict1 @@ -173,7 +171,7 @@ else: other = dict1 ``` -We can use the `timeit` [magic command](https://ipython.readthedocs.io/en/stable/interactive/magics.html) in either a Jupyter notebook or an IPython console to time our functions (Note: each `timeit` must be run in a separate notebook cell, and `%%timeit` must be the topmost command in the cell). +我们可以在Jupyter记事本或IPython控制台种使用 `timeit` [魔法命令](https://ipython.readthedocs.io/en/stable/interactive/magics.html)(magic command)来记录我们函数花的时间(注:每次 `timeit` 都必须在不同的记事本小节中运行,且 `%%timeit` 必须是小节的第一行命令)。 ```python a = {} @@ -192,13 +190,13 @@ opt_merge_max_mappings(a, b) 455 µs ± 12.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` -This is a relatively small speedup despite the rather stark example we cooked up. +考虑到我们人为建立的例子的极端性,这个速度提升还是比较小的。 -## Extended Problem: Merging Arbitrary Numbers of Dictionaries +## 额外问题:合并任意多的词典 -There is no reason that our function should only be able to merge two dictionaries, it should be easy to accommodate an arbitrary number of inputs: +我们的函数没有任何理由仅仅合并两个词典。它应该可以合并任意多的词典: ```python >>> a = dict(a=0, b=100, c=3) @@ -210,36 +208,35 @@ There is no reason that our function should only be able to merge two dictionari {'a': 10, 'b': 100, 'c': 50, 'd': -70} ``` -Before you write your solution, consider the following: -1. How do you write a function signature so that it can handle an arbitrary number of input dictionaries? -2. How should your function handle zero inputs? How about one input? +在你写答案之前,请考虑以下: +1. 你该如何编写函数签名使其能够接受任意多的词典呢? +2. 你的函数该如何处理0个输入的情况?1个输入呢? -## Generalized Solution -Addressing point #1, we will want to use the `*args` syntax in our function signature so that [it can accommodate an arbitrary number of dictionaries](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#Accommodating-an-Arbitrary-Number-of-Positional-Arguments). Thus all of the dictionaries fed to our function will be packed into a tuple that can be accessed via `args` (or whatever variable name we use in our signature). +## 解 +为了解决问题#1,我们将会想要在函数的签名中使用 `*args` 语法来[接受任意多的词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#支持任意多的位置参数)。因此,所有输入到我们函数中的词典都会被打包成一个元组并可以通过 `args`(或我们使用的随便什么变量名)来访问。 -Regarding point #2, we can handle the case of receiving no inputs by simply returning an empty dictionary. We will also see that handling the case of a single input is more subtle than one might guess. This point will be discussed further once the solution is presented. +为了解决问题#2,我们可以在收到0个输入时返回空词典。同时,请注意,收到1个输入的情况可能比我们想象的更微妙一点。我们将在展示解之后再多做讨论。 -Our solution is to create an empty dictionary, `merged`, and to simply iterate over each mapping of each input dictionary and perform our merging as we did above: +本解创建了一个空词典 `merged`,迭代每一个输入词典的对应关系,并执行像之前一样的合并操作: ```python def merge_max_mappings(*dicts): - """ Merges an arbitrary number of dictionaries based on the - maximum value in a given mapping. - + """ 根据对应关系中的最大值合并任意多的词典。 + Parameters ---------- dicts : Dict[Any, Comparable] - + Returns ------- Dict[Any, Comparable] - The merged dictionary + 合并的词典 """ merged = {} - for d in dicts: # `dicts` is a tuple storing the input dictionaries - for key in d: + for d in dicts: # `dicts` 是一个储存输入词典的元组 + for key in d: if key not in merged or d[key] > merged[key]: merged[key] = d[key] return merged @@ -247,16 +244,16 @@ def merge_max_mappings(*dicts): -### Handling Zero Inputs -See that our function returns an empty dictionary if it is not passed any inputs, this is because `dicts` will be an empty tuple and thus our loop over it will immediately exit, returning an unpopulated `merged`: +### 处理零个输入 +请注意,我们的函数在没有收到任何输入时会返回一个空词典。这是因为 `dicts` 将会是一个空元组,因此我们的循环会直接退出并返回一个空的 `merged`: ```python >>> merge_max_mappings() {} ``` -While you may have thought to have returned `None` in the case of there being no dictionaries to merge, returning an empty dictionary is much better behavior as code downstream from our function will only need to accommodate one type of output. Additionally, our function's docstring promises that it will return a dictionary and we should always abide by this contract. +虽然你可能会想要在这种情况下返回 `None`,但是返回空词典是一个更加可取的行为,因为使用这个函数的代码如此只需要处理一种输出类型。同时,我们函数的docstring保证它将返回一个词典,而我们应该永远满足这个协议。 -### Handling One Input -In the case that our function is passed a single dictionary, our function effectively makes a (shallow) copy of that dictionary and returns it. Suppose we tried to be clever and wrote our function to pass a single dictionary through; e.g. +### 处理一个输入 +当我们函数只收到一个输入词典时,它最后会返回一个该词典的(浅层)复制品。假设我们试图耍聪明并让我们的代码在只收到单个词典时直接返回该词典,如: ```python def bad_merge_max_mappings(*dicts): @@ -264,27 +261,27 @@ def bad_merge_max_mappings(*dicts): return dicts[0] merged = {} for d in dicts: - for key in d: + for key in d: if key not in merged or d[key] > merged[key]: merged[key] = d[key] return merged ``` -What is wrong with this solution? The problem is similar to the one that we considered above; our function always returns a dictionary that is independent from its inputs, meaning that mutating the merged dictionary has no impact on any of the inputs dictionaries. This is no longer the case when we receive a single dictionary - here the "merged" dictionary is simply a reference to the input. Any subsequent mutation of the output dictionary will also mutate the input dictionary, and vice versa. This unanticipated behavior could create very hard-to-find bugs in your code! +这个解有什么问题呢?这个问题和我们以上考虑过的类似;我们的函数永远应该返回一个和输入参数无联系的词典,也就是说修改合并的词典不应该对输入词典有任何影响。在我们收到单个词典的时候,我们打破了这个规则——在这里“合并的”词典仅仅是输入词典的引用。任何对输出词典的操作都会修改输入词典,且反之亦然。这个意料之外的行为可能会导致你代码中出现很难找出的错误! -It is best to not try to handle specialized cases like this, when the general code behaves appropriately to begin with. +当你的简单代码已经足够全面合理时,你没有必要专门处理这样的特殊情况。 -## Extra Challenges -- Write tests for your functions where the dictionary keys aren't strings and the values aren't numbers. -- What if you wanted to merge values based on a criterion other than the maximum value? Try rewriting the function so that a comparison function can passed in as an argument. Remember that functions, once defined, are objects just like integers and strings - they can be passed as arguments into other functions. +## 额外挑战 +- 为你的函数编写输入键不是字符串且值不是数字的词典的测试。 +- 当你想用的值不是最大值,而是某个其它标准决定的值时该怎么做?尝试重写你的函数使其可以接受一个对比函数。请回忆,函数在定义后就是一个对象,其本质与整数和字符串一样——它们都可以作为参数输入进其它函数中。 -The following code is correct, but really bad: +以下代码是正确的,但其质量极差: ```python def gross_merge_max_mappings(*dicts): - """merges dicts""" + """合并词典""" merged = {} for i in range(len(dicts)): for j in dicts[i]: @@ -296,5 +293,5 @@ def gross_merge_max_mappings(*dicts): continue return merged ``` -Compare this code to the solution that we devised, and enumerate all of the stylistic mistakes that are made here. Appreciate how simple and readable our code is by comparison and make a promise to yourself that you will not write code like this. +将以上代码和我们提供的解进行对比,并枚举在此所有的风格错误。体会一下我们编写的代码相比之下有多么简单易懂,并向自己承诺永远不要编写这样的垃圾代码。 diff --git a/Python/Module2_EssentialsOfPython/Problems/Palindrome.md b/Python/Module2_EssentialsOfPython/Problems/Palindrome.md index 4921dcb..2b3eeb5 100644 --- a/Python/Module2_EssentialsOfPython/Problems/Palindrome.md +++ b/Python/Module2_EssentialsOfPython/Problems/Palindrome.md @@ -4,26 +4,26 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Palindrome Exercise, Difficulty: Easy, Category: Practice Problem :keywords: string, palindrome, practice problem -``` + -# Is Palindrome -> A palindrome is a string that reads the same from left to right and from right to left. Strings like `racecar` and `Live on time, emit no evil` are palindromes. Notice that only valid alphanumeric characters are accounted for and that palindromes are not case-sensitive. Given a string, return whether or not it is a palindrome. +# 回文判断 +> 回文(palindrome)是从左到右和从右到左读起来都一样的字符串。比如说,`racecar` 和 `Live on time, emit no evil` 都是回文。请注意,我们仅仅考虑字母和数字,且不分大小写。在得到输入字符串后,请判断它是否是回文。 ```python -# example behavior +# 范例行为 >>> is_palindrome("Step on no pets!") True >>> is_palindrome("'Tis not a palindrome") @@ -32,8 +32,8 @@ False True ``` -## Tips -[str.isalnum](https://docs.python.org/3/library/stdtypes.html#str.isalnum) returns whether or not a string has purely alphanumeric characters (it works for single-character strings too). +## 提示 +[str.isalnum](https://docs.python.org/3/library/stdtypes.html#str.isalnum)返回某字符串是否纯粹由数字和字母字符组成(对单个字符的字符串也可以用)。 ```python >>> "I love Python".isalnum() False @@ -41,24 +41,23 @@ False True ``` -Consider using this along with `str.lower` to filter out ignored characters and to normalize all of the character casing in the string before assessing whether or not it is a palindrome. +尝试将其与 `str.lower` 一起使用来过滤所有非数字字母符号并将所有字符小写化,然后再进行回文判断。 -## Solution -The simplest solution to this problem is the following, where we make use of the `str.join` function as well as slicing with a negative step: +## 解 +本题最简单的解如下。我们使用了 `str.join` 函数以及步距为负的切片: ```python def is_palindrome(input_str): - """ Given a string, determine if it is a palindrome. - Whitespaces, character-casing, and non-alphanumeric - characters are all ignored. - + """ 判断某字符串是否为回文。忽略空格, + 字符大小写,以及非字母数字的字符 + Parameters ---------- s: str - Input string - + 输入字符串 + Returns ------- bool @@ -67,12 +66,12 @@ def is_palindrome(input_str): return filtered_str == filtered_str[::-1] ``` -See that `(c.lower() for c in input_str if c.isalnum())` has the form of a [filtering generator comprehension](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#Creating-your-own-generator:-generator-comprehensions). Thus, +注意 `(c.lower() for c in input_str if c.isalnum())` 使用了[有过滤条件的生成器理解](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Generators_and_Comprehensions.html#创建你自己的生成器:生成器理解)。因此, ```python "".join(c.lower() for c in input_str if c.isalnum()) ``` -is equivalent to the long-form code: +等值于以下的代码块: ```python filtered_str = "" @@ -80,19 +79,19 @@ for char in input_str: if char.isalnum(): filtered_str += char.lower() ``` -The generator comprehension expression is not only more concise and readable, but its use of `str.join` also makes it a more efficient means for constructing a new list. Each call to `filtered_str += c.lower()` in the long-form code creates a new string in memory, whereas `str.join` forms a single string as it consumes the input iterable. +生成器表达式不仅更加简短易读,且其对 `str.join` 的使用使得创建新列表更加高效。在以上代码块中每次调用 `filtered_str += c.lower()` 都会在内存中创建一个新字符串,而 `str.join` 在它消耗可迭代物时仅仅使用单个字符串。 -Next, [recall that](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Slicing) `seq[::-1]` slices a sequence with a step of -1, which produces the sequence in *reverse order*. Thus `filtered_str == filtered_str[::-1]` allows us to compare the first character in `filtered_str` with the last and so on. This is equivalent to: +接下来,[请回忆](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#切片),`seq[::-1]` 使用的步距-1的切片将会返回序列的*反向*版本。因此,`filtered_str == filtered_str[::-1]` 允许我们对比 `filtered_str` 中的第一个字符和原本字符串的倒数第一个字符,如此继续。因此,这等值于: ```python is_equal = True -for i in range(len(filtered_str)//2): # recall: 5//2 -> 2, 6//2 -> 3 +for i in range(len(filtered_str)//2): # 请回忆:5//2 -> 2, 6//2 -> 3 if filtered_str[i] != filtered_str[-(i+1)]: is_equal = False break ``` -The only downside to using slicing to perform this comparison is that it requires that a copy of `filtered_str` be created, whereas using the explicit for-loop does not. +使用切片来进行这个对比的唯一坏处在于它需要复制一份 `filtered_str`,而显性的for循环不需要。 -We must note that the performance differences pointed out here should only concern us if `is_palindrome` is potentially a performance bottleneck for our code. Although we want the reader to develop an intuition for writing efficient Python code, we discourage mangling code for the sake of premature optimization. +在这里指出的效率考量仅仅在 `is_palindrome` 可能是我们整体代码的效率瓶颈时才值得进行。虽然我们希望读者能够发展编写高效Python代码的直觉,但我们不推荐读者为了过早地优化代码来将代码改得太过难懂。 diff --git a/Python/Module2_EssentialsOfPython/Scope.md b/Python/Module2_EssentialsOfPython/Scope.md index b784bdd..c750be5 100644 --- a/Python/Module2_EssentialsOfPython/Scope.md +++ b/Python/Module2_EssentialsOfPython/Scope.md @@ -4,87 +4,86 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: variable score and namespaces in python, Difficulty: Medium, Category: Section :keywords: variable, namespace, function, scope, shadowing -``` + -# Scope +# 作用域 -A valuable aspect of the "encapsulation" provided by functions is that the function's input argument variables, and any variables defined within the function, cannot be "seen" nor accessed outside of the function. That is, these variables are said to have a restricted **scope**. +函数“封装”(encapsulation)提供的一大好处在于你无法在函数外面“看到”或访问参数变量或其中定义的任何其它变量。也就是说,这些变量的**作用域**(scope)是有限的。
-**Definition**: +**定义**: -The **scope** of a variable refers to the context in which that variable is visible/accessible to the Python interpreter. +一个变量的**作用域**指其在Python直译器眼中可见/可访问的环境。
-Until our work with comprehension-statements and functions, we had only encountered variables that have **file scope**. This means that a variable, once defined, is visible to all parts of the code contained in the same file. Variables with file scope can even be accessed *within functions*. By contrast, the variables defined within a function or as input arguments to a function have a **restricted scope** - they can only be accessed within the context of the function: +直到我们理解语句和函数的讨论之前,我们仅仅遇到过有**文件作用域**(file scope)的变量。这意味着被定义后,该变量对任何相同文件中的代码而言都可见。有着文件作用域的变量甚至可以*在函数内*使用。相比文件作用域,函数中定义的变量或函数的输入参数则有着**有限作用域**(restricted scope)——它们只能在函数内使用: ```python -x = 3 # `x` has file scope. It can be even be accessed - # within a function, even if it isn't passed to - # the function as an argument +x = 3 # `x` 有着文件作用域。就算它没有作为参数输入到函数中, + # 它也可以在其中被访问 -# `my_func` has file scope (after it is defined) +# `my_func` 在其被定义后有着文件作用域 def my_func(y): - func_var = 9 + x # `x` will have the value 3 - # the scope of `y` and `func_var` is restricted to this function + func_var = 9 + x # `x` 的值将为3 + # 变量 `y` 和 `func_var` 的作用域限制在本函数中 return y -# `func_var` and `y` do not exist here -print(func_var) # raises NameError: name `func_var` not defined -print(y) # raises NameError: name `y` not defined +# `func_var` 和 `y` 在此不存在 +print(func_var) # 导致 NameError:名字 `func_var` 未定义 +print(y) # 导致 NameError:名字 `y` 未定义 ``` -Python's scoping rules are quite liberal compared to those of other languages, like C++. In most situations, Python will give variables file scope. Let's briefly survey the various contexts in which variables are defined, along with their corresponding scoping rules. Assume that the following code represents the entire contents of the Python script "example_scope.py": +Python的作用域规则其实相比其他如C++的语言相当直接。在大部分情况下,Python会给予变量文件作用域。让我们快速总结一下定义变量的不同环境以及它们相对应的作用域规则。假设以下代码代表着Python脚本“example_scope.py”的全部内容: ```python -# this demonstrates scope of variables in different contexts -# nothing meaningful is computed in this file +# 演示变量在不同情况下的作用域 +# 本文件并不计算任何有意义的结果 -from itertools import combinations # `combinations` has file scope +from itertools import combinations # `combinations` 有文件作用域 -# `my_func` has file scope -# `in_arg1` has restricted scope -# `in_arg2` has restricted scope -# `func_block` has restricted scope +# `my_func` 有文件作用域 +# `in_arg1` 有有限作用域 +# `in_arg2` 有有限作用域 +# `func_block` 有有限作用域 def my_func(in_arg1, in_arg2="cat"): func_block = 1 return None -# `file_var` has file scope -# `comp_var` has restricted scope +# `file_var` 有文件作用域 +# `comp_var` 有有限作用域 file_var = [comp_var**2 for comp_var in [-1, -2]] -# `if_block` has file scope +# `if_block` 有文件作用域 if True: if_block = 2 else: if_block = 3 -# `it_var` has file scope -# `for_block` has file scope +# `it_var` 有文件作用域 +# `for_block` 有文件作用域 for it_var in [1, 2, 3]: for_block = 1 -# `while_block` has file scope +# `while_block` 有文件作用域 while True: while_block = None break ``` -In the preceding code, the following variables have *file scope*: +在以上代码中,以下变量有着*文件作用域*: - `combinations` - `my_func` @@ -94,7 +93,7 @@ In the preceding code, the following variables have *file scope*: - `for_block` - `while_block` -whereas the following variables have *restricted scope*: +而以下变量有着*有限作用域*: - `in_arg1` - `in_arg2` @@ -102,51 +101,51 @@ whereas the following variables have *restricted scope*: - `comp_var` -In C++, the variables `if_block`, `it_var`, `for_block`, and `while_block` all would have had restricted scopes - these variables would not be defined outside of their respective if/for/while blocks. +在C++中,变量 `if_block`,`it_var`,`for_block`,和 `while_block` 会有着有限作用域——这些函数在它们对应的if/for/while区块外不会被定义。
-**Takeaway**: +**经验**: -Variables defined within a function have a *restricted scope* such that they do not exist outside of that function. Most other contexts for defining variables in Python produce variables with *file scope* (i.e. they can be accessed anywhere in the file's code, subsequent to their definition). +在函数中定义的变量有着*有限作用域*。这将导致它们在函数外不存在。大部分其它情况下定义的Python变量都有着*文件作用域*(也就是说它们在定义后可以被同文件的任何代码使用)。
-## Variable Shadowing -What happens when a file-scope variable and a function-scope variable share the same name? This type of circumstance is known as **variable shadowing**. Python resolves this by giving precedence to the variable *with the most restricted scope*, when inside that scope: +## 变量重影 +当一个文件作用域的变量和一个函数作用域的变量有着同样名字时会发生什么?这种情况叫做**变量重影**(variable shadowing)。Python通过优先使用可用作用域中*最受限制的作用域*的变量来解决这个冲突: ```python x = 2 y = 3 def func(x): - # input-arg `x` overrides file-scope version of `x` - y = 5 # overrides file-scope version of `y` + # 输入参数 `x` 凌驾于文件作用域版本的 `x` 之上 + y = 5 # 凌驾于文件作用域版本的 `y` 之上 return x + y -# `x` is 2 here, once again -# `y` is 3 here, once again +# `x` 在这里是 2 +# `y` 在这里是 3 -print(func(-5)) # prints 0 -print(x, y) # prints 2 3 +print(func(-5)) # 打印 0 +print(x, y) # 打印 2 3 ``` -and similarly, +相似的: ```python it = "cow" def func(): - it = "dog" # overrides file-scope version of `it` - my_list = [it**2 for it in [1, 2, 3]] # within the list comprehension, the func-scope `it` is overridden - # `it` is "dog" here, once again + it = "dog" # 凌驾于文件作用域版本的 `it` 之上 + my_list = [it**2 for it in [1, 2, 3]] # 在列表理解中,函数作用域版本的 `it` 被覆盖了 + # `it` 在这里是 "dog" return None -# `it` is "cow" here, once again +# `it` 在这里是 "cow" ``` -## Links to Official Documentation +## 官方说明文档链接 -- [Scopes and namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) -- [Python's execution model](https://docs.python.org/3/reference/executionmodel.html) +- [作用域和命名空间](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) +- [Python的执行模型](https://docs.python.org/3/reference/executionmodel.html) diff --git a/Python/Module2_EssentialsOfPython/SequenceTypes.md b/Python/Module2_EssentialsOfPython/SequenceTypes.md index 2579019..baf7729 100644 --- a/Python/Module2_EssentialsOfPython/SequenceTypes.md +++ b/Python/Module2_EssentialsOfPython/SequenceTypes.md @@ -4,68 +4,67 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: understanding python sequences, Difficulty: Easy, Category: Section :keywords: list, tuple, string, slice, index, negative index, get item, pop, append, examples -``` + -# Sequence Types +# 序列类型
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +本文各处的阅读理解练习旨在帮助你练习使用文章中的知识点。练习题的答案可以在本页结尾找到。
-The following objects are all example of sequences: +下列对象都是序列(sequence)的种类: ```python -# examples of sequences +# 序列的例子 -# a list +# 列表(list) [0, None, -2, 1] -# a string +# 字符串(string) "hello out there" -# a tuple +# 元组(tuple) ("a", False, 0, 1) -# a NumPy array +# NumPy数组 numpy.ndarray([0.2, 0.4, 0.6, 0.8]) ``` -Being able to work with sequences of objects/data is so important that it warrants us to take our first (relatively) deep dive into Python. The preceding reading introduced Python lists and strings, two important objects that are built into the Python language. Although quite distinct from one another in terms of what they can contain, *lists and strings are both types of sequences* - they store a finite collection of objects whose ordering matters (e.g. `"cat"` and `"tac"` should be considered distinct strings). As such, lists, strings, and the other sequence types in Python all share a common interface for allowing users to inspect, retrieve, and summarize their contents. +因为操作对象/数据序列的能力极其重要,我们第一课(相对)深入的Python探讨将会学习序列类型。前面的阅读向读者介绍了Python的列表和字符串。虽然两者能存储的内容不同,*列表和字符串都是一种序列*——它们能够存储一组有限多的有顺序的对象(比如说 `"cat"` 和 `"tac"` 虽然成员字符相同,但是其实是两个不一样的字符串)。因此,列表,字符串,和其它Python的序列类型共享一个常用的接口来帮助用户查阅,调用,和总结它们的内容。 -In this section, we will: +在本节中,我们将: -- Introduce tuples, the last built-in sequence type that we have yet to encounter. -- Demonstrate the common interface that can be used to inspect and summarize the contents of a sequence. -- Detail the all-important indexing scheme used by Python, which will allow us to access specific items or subsequences from a sequence. +- 介绍元组——我们将见到的最后一种内置序列类型。 +- 展示用来查阅和总结序列内容的通用接口。 +- 细致讨论Python的检索系统。我们可以用它来查阅序列具体的成员或子序列。 -## Tuples -The last built-in sequence type that we have yet to encounter is the `tuple` type. A tuple is very similar to a list, in that it can store a sequence of arbitrary objects (a mix of numbers, strings, lists, other tuples, etc.). Where lists are constructed using square-brackets, tuples use parentheses: +## 元组 +最后一个我们还未讨论的内置序列类型叫做 `tuple`(元组)类型。元组和列表相似,都可以存储任何对象(数字,字符串,列表,其它元组,或多种对象,等等)。和列表的方括号不同的是元组由圆括号创建: ```python -# creating a tuple ->>> x = (1, "a", 2) # tuple with 3 entries +# 创建元组 +>>> x = (1, "a", 2) # 有三个物件的元组 -# (3) does not make a tuple with one entry -# you must provide a trailing comma in this -# instance ->>> y = (3,) # a tuple with 1 entry +# (3) 并不能创建只有一个物件的元组 +# 在这个情况下,你必须在最后添加一个额外的逗号 +>>> y = (3,) # 有一个对象的元组 >>> type(x) tuple @@ -76,36 +75,36 @@ True
-**Checking multiple types**: +**检查多种类型**: -`isinstance` can be used to check multiple types at once, by supplying it a tuple of types. That is, +通过输入一个包含多类型的元组,你可以用 `isinstance` 来一次性检查多种类型。如下: ```python isinstance(x, (tuple, list, str)) ``` -Will check if `x` is a tuple *or* a list *or* a string. +这将检查 `x` 是否是元组*或*列表*或*字符串。
-Unlike a list, *once a tuple is formed, it cannot be changed*. That is, a tuple is *immutable*, whereas a list is *mutable*. Tuples generally consume less memory than do lists, since it is known that a tuple will not change in size. Furthermore, tuples come in handy when you want to ensure that a sequence of data cannot be changed by subsequent code. +和列表不同的是,*当你创建元组之后,你无法修改它*。也就是说,元组是*不可变*(immutable)的,而列表是*可变*(mutable)的。元组一般相比列表会使用更少的内存,因为我们提前知道元组的大小不会改变。另外一个元组的好用点在于它保证存储的数据不会被之后的代码给改变。 ```python -# the contents of a list can be changed: it is "mutable" +# 列表的内容可以被修改;列表是“可变”的 >>> x = [1, "moo", None] >>> x[0] = 2 >>> x [2, 'moo', None] -# the contents of a tuple cannot be changed: it is "immutable" ->>> y = (1, "moo", None) # (a, b, ...) creates a tuple +# 元组的内容不可以被修改;元组是“不可变”的 +>>> y = (1, "moo", None) # (a, b, ...) 创建一个元组 >>> y[0] = 2 TypeError: 'tuple' object does not support item assignment ``` -`tuple` can be used to convert other sequences (other iterables, more generally) into tuples. `str` and `list` behave similarly. +你可以用 `tuple` 来将其它序列(或广义来讲,其它任何可迭代物)转化成元组。这和 `str` 和 `list` 的行为类似。 ```python -# `tuple` can create a tuple out of other sequences +# `tuple` 可以利用其它序列来创建元组 >>> x = [2, 4, 8] >>> y = tuple(x) @@ -118,12 +117,12 @@ TypeError: 'tuple' object does not support item assignment -## Working with sequences -The following summarizes the common interface that is shared by Python's different types of sequence, which includes lists, tuples, and strings. This interface allows you to inspect, summarize, join, and retrieve members from any variety of sequence. +## 操作序列 +下文将总结不同Python序列类型(包括列表,元组,和字符串)的通用界面。此界面将允许你查看,总结,合并,和获取序列的成员。 -**Checking if an object is contained within a sequence:** `obj in seq` +**检查某对象是否为序列成员**:`obj in seq` ```python -# using 'in' and 'not in' for membership checking +# 利用 'in' 和 'not in' 检查对象是否为序列成员 >>> x = (1, 3, 5) >>> 3 in x @@ -135,44 +134,42 @@ False >>> 0 not in x True -# strings can also test for sub-sequence membership +# 你可以检查字符串是否为其它字符串的子序列 >>> "cat" in "the cat in the hat" True -# you cannot test for sub-sequence membership in other -# types of sequences +# 而其它序列类型不支持子序列检查 >>> [1, 2] in [1, 2, 3, 4] False -# the list [1, 2] must be an element of the list -# to be seen as a member +# 只有当 [1, 2] 为列表中的项目时才会被视作列表成员 >>> [1, 2] in [None, [1, 2], None] True ``` -**Concatenating sequences:** `seq1 + seq2` +**连接序列:**`seq1 + seq2` ```python -# concatenating sequences with '+' ->>> [1, 2] + [3, 4] # creates a new list +# 通过 '+' 来粘连两个序列 +>>> [1, 2] + [3, 4] # 这将创建一个新序列 [1, 2, 3, 4] >>> "c" + "at" "cat" ``` -**Repeated concatenation of a sequence:** `n*seq1` or `seq1*n` +**重复连接某序列**:`n*seq1` 或 `seq1*n` ```python -# equivalent to `cat + cat + cat` ->>> "cat" * 3 # creates a new string +# 和 `cat + cat + cat` 等值 +>>> "cat" * 3 # 创建一个新字符串 'catcatcat' ->>> 4 * (1, 5) # creates a new tuple +>>> 4 * (1, 5) # 创建一个新元组 (1, 5, 1, 5, 1, 5, 1, 5) ``` -**Asking for the number of members in a sequence:** `len(seq)` +**检查序列成员数**:`len(seq)` ```python -# getting the length of a sequence +# 查看序列的长度 >>> len("dog") 3 @@ -183,24 +180,24 @@ True 0 ``` -**Getting the index of the first occurrence of** `x` **in a sequence**: `seq.index(x)` +**查看序列中** `x` **第一次出现的位置的索引**:`seq.index(x)` ```python ->>> "cat cat cat".index("t") # 't' first occurs at index-2 +>>> "cat cat cat".index("t") # 't' 第一次出现在索引(index)2 2 -# `index` doesn't look within sequences contained by the outer sequence -# e.g. it sees 1, 2, and "moo", not 1, 2, "m", "o", "o" +# `index` 并不会检查序列中包含的成员序列 +# 例,它会检查 1,2,和 "moo",而不是1,2,“m”,“o”,“o” >>> [1, 2, "moo"].index("m") ValueError: 'm' is not in list ``` -**Counting the number of occurrences of** `x` **in a sequence**: `seq.count(x)` +**返回序列中** `x` **出现的次数**:`seq.count(x)` ```python >>> "the cat in the hat".count("h") 3 -# `count` doesn't look within sequences contained by the outer sequence -# thus is doesn't "see" the 1 within `[1, 2]`. +# `count` 不会检查序列中包含的成员序列 +# 因此,它不会“看到” `[1, 2]` 中的 1。 >>> [1, [1, 2], "111", 1].count(1) 2 ``` @@ -208,19 +205,19 @@ ValueError: 'm' is not in list
-**Reading Comprehension: Basics of sequences** +**阅读理解:序列基础** -1\. Change the list `[True, None, 22]` into a tuple. +1\. 将列表 `[True, None, 22]` 转化成元组。 -2\. How many sequence-types have we discussed thus far? Which of these produce objects that are immutable? Which of these produce objects that are mutable? For those types that are mutable, write a piece of example code that mutates an object. +2\. 到现在,我们讨论了多少种序列类型?其中哪些创建不可变对象?哪些创建可变对象?在可变类型中选择一个并编写修改其成员对象的范例代码。
-### Introducing Indexing and Slicing -We can access individual items from a sequence by specifying the *index* of that item. Python ascribes the 1st entry in a sequence index-0, the second entry index-1, and so on. +### 索引和切片简介 +我们可以通过提供序列中单个成员的*索引*(index)来访问此物件。Python序列的第一个成员的索引是0,第二个是1,如此下去。 ```python -# accessing individual items from a sequence via indexing +# 通过索引来访问序列的单个物件 >>> x = "abcdefg" >>> x[0] "a" @@ -229,16 +226,16 @@ We can access individual items from a sequence by specifying the *index* of that "c" ``` -We can also "slice" a sequence, specifying a start-index and stop-index, and return a subsequence of the items contained within the slice: +我们也可以切片(“slice”)序列,也就是通过提供起始索引和结尾索引来返回其中包含的子序列: ```python -# "slicing" a sequence produces a subsequence of its contents ->>> x[0:3] # include items 0, 1, 2 (3 is excluded) +# 通过“切片”来提供序列内容的子序列 +>>> x[0:3] # 这子序列包含索引为0,1,2(注意不包含3)的成员 "abc" ``` -It is critical to have a good grasp of how to access a sequence's members and subsequences by using indexing and slicing. This indexing scheme will also appear in our work with NumPy arrays. We will proceed by providing a detailed rundown of Python's indexing and slicing mechanisms. +熟练访问序列成员和子序列是极其重要的技能。索引功能也会在我们操作NumPy数组(array)时出现。接下来,让我们来具体描述Python的索引和切片功能。 -### Indexing -Python allows you to retrieve individual members of a sequence by specifying the *index* of that member, which is the integer that uniquely identifies that member's position in the sequence. *Python implements 0-based indexing for its sequences*, and also permits the use of negative integers to count from the end of the sequence. Consider the string `"Python"`. The following diagram displays the indices for this sequence: +### 索引 +Python允许你通过序列中单个成员的*索引*(index),一个识别成员在序列中位置的独特整数,来获取该成员。*Python使用从0开始的索引模式*,并允许你使用负数来从序列结尾往开头数。拿字符串 `"Python"` 来说,接下来的图表将显示该序列的索引: ``` +---+---+---+---+---+---+ | P | y | t | h | o | n | @@ -247,9 +244,9 @@ Python allows you to retrieve individual members of a sequence by specifying the -6 -5 -4 -3 -2 -1 ``` -The first row of numbers gives the position of the indices 0…5 in the string; the second row gives the corresponding negative indices. +第一行的数字提供了字符串0到5的索引;第二行提供了对应的负索引。 -**Positive Indices** +**正索引** - 0 $\rightarrow$ P - 1 $\rightarrow$ y @@ -258,7 +255,7 @@ The first row of numbers gives the position of the indices 0…5 in the string; - 4 $\rightarrow$ o - 5 $\rightarrow$ n -**Negative Indices** +**负索引** - -6 $\rightarrow$ P - -5 $\rightarrow$ y @@ -267,23 +264,23 @@ The first row of numbers gives the position of the indices 0…5 in the string; - -2 $\rightarrow$ o - -1 $\rightarrow$ n -Given this indexing scheme, Python reserves the use of square brackets following a variable name or object, as the "get-item" syntax: `seq[index]`. +通过此索引模式,Python保留变量名或对象后的方括号语法来允许用户“获取成员”:`seq[index]`。 ```python -# Demonstrating indexing into sequences +# 演示序列索引 >>> x = [1, 2, 3, 4] -# this is known as the "get-item" syntax ->>> x[0] # indexing starts at 0 +# 这叫做“获取成员”语法。 +>>> x[0] # 索引从0开始 1 ->>> x[-4] # each entry has a positive index and negative index +>>> x[-4] # 每个成员都有着对应的正索引和负索引 1 ->>> x[-1] # negative indexing is relative to the end of the sequence +>>> x[-1] # 负索引是相对序列结尾而言的 4 ->>> "cat"[2] # you can index directly into a sequence-object +>>> "cat"[2] # 你可以直接检索序列对象 't' >>> (True, False)[-1] @@ -292,94 +289,94 @@ False
-**Takeaway**: +**经验**: -To "index into" a sequence is to retrieve a single member by specifying an integer index, that indicates the place of that member in the sequence: `seq[index]`. Python uses a zero-based indexing system, meaning that the first element in a sequence is located at position 0. Negative indices allow you to refer to an item's position relative to the end of the list. +对一个序列“索引”指的是通过提供序列中单个成员的索引——也就是表达成员在序列中位置的整数——来获取它:`seq[index]`。Python使用一个从0开始的索引系统,也就是说序列中第一个成员是索引0。负索引允许你通过对象相对序列结尾的位置来获取它。
-### Slicing -Slicing a sequence allows us to retrieve a subsequence of items, based on the indexing scheme that we reviewed in the preceeding subsection. Specifying a slice consists of: +### 切片 +我们可以利用类似前文索引的切片(slicing)来获取列表的子序列。一个切片(slice)包含了以下的部分: -- A start-index: the sequence-position where the slice begins (this item is *included* in the slice). -- A stop-index: the sequence-position where the slice ends (this item is *excluded* from the slice). -- A step-size, which permits us to take every item within the start & stop bounds, or every *other* item, and so on. It is important to note that a negative step-size permits us to traverse a sequence *in reveresed order*. +- 起始索引(start-index):切片第一个物件的索引(索引指向的成员将*会被包含*在该切片中)。 +- 结尾索引(stop-index):切片结尾的索引(索引指向的成员*不会被包含*在切片中)。 +- 步距(step-size):这将允许我们获取起始和结尾中的每个成员,或每*两个*成员,或每*n个*成员。负步距将允许从结尾往开始*反向*获取每n个成员。 -The basic syntax for slicing is: `seq[start:stop:step]`, using colons to separate the start, stop, and step values. +切片的基本语法为:`seq[start:stop:step]`。注意使用冒号“:”来分别起始,结尾,和步距。 ```python -# demonstrating the basics of slicing a sequence +# 演示序列切片 >>> seq = "abcdefg" -# start:0, stop:4, step:1 +# start:0, stop:4,step:1 >>> seq[0:4:1] 'abcd' -# start:1, stop:4, step:1 +# start:1,stop:4,step:1 >>> seq[1:4:1] 'bcd' -# start:1, stop:5, step:2 ->>> seq[0:5:2] # get every other entry within [start, stop) +# start:1,stop:5,step:2 +>>> seq[0:5:2] # 获取 [start, stop) 中的每两个成员 'ace' -# starting and stopping at the same index produces an empty sequence -# start:0, stop:0, step:1 +# start和stop同一个索引时会得到空序列 +# start:0,stop:0,step:1 >>> seq[0:0:1] '' ``` -Slicing provides sensible default start, stop, and step values. Their default values are: +切片默认的start,stop,和step值都很实用。具体如下: -- start: 0 -- stop: `len(seq)` -- step: 1 +- start:0 +- stop:`len(seq)` +- step:1 -You can omit any of these values or specify `None` in that entry to use the default value. You can omit the second colon entirely, and the slice will use a step-size of 1. +对其中任何一个值,你可以通过不提供值或提供 `None` 来使用默认值。你也可以不提供第二个冒号和后面的步距来使用默认的步距1。 ```python -# using default start, stop, and step values +# 使用默认的start,stop,和step值 >>> seq = "abcdefg" -# start: 0, stop: 7, step: 1 ->>> seq[:] # equivalent: `seq[None:None]` +# start:0,stop:7,step:1 +>>> seq[:] # 和 `seq[None:None]` 等值 'abcdefg' -# start: 0, stop: 7, step: 2 +# start:0,stop:7,step:2 >>> seq[::2] 'aceg' ``` -Negative values can also be used in a slice. Specifying a negative step-value instructs the slice to traverse the sequence *in reverse order*. In this case, the default start and stop values will change so that `seq[::-1]` produces the sequence in reverse. +你也可以在切片中使用负数。负步距将会*反向*迭代选中的序列。在这个情况下,默认的起始和结尾索引将会变成使得 `seq[::-1]` 提供该序列的反向版本的值。 ```python -# using a negative step size reverses the order of the sequence +# 使用负步距来提供序列的反向版本 >>> seq[::-1] 'gfedcba' ``` -As we saw with using negative indices, specifying negative start/stop values in a slice permits us to indicate indices relative to the end of the list. +和负索引一般,在切片中使用负起始或结尾值允许我们表达相对于序列结尾的位置。 ```python -# a slice returning the last two values of the sequence +# 该切片将返回序列的最后两个值 >>> seq[-2:] 'fg' -# a slice returning all but the last two values of the sequence +# 该切片将返回除了最后两个值之外的列表序列 >>> seq[:-2] 'abcde' ``` -Although the colon-syntax for slicing, `seq[start:stop:step]`, appears nearly ubiquitously in Python code, it is important to know that there is a built-in `slice` object that Python uses to form slices. It accepts the same start, stop, and step values, and produces the same sort of slicing behavior: +虽然切片的冒号语法 `seq[start:stop:step]` 在Python代码中随处可见,你应知道Python使用一个内置的 `slice` 对象来创建切片。它接受一样的start,stop,和step值,并提供一样的切片行为: ```python -# using the `slice` object explicitly +# 显性使用 `slice` 对象 >>> seq = "abcdefg" >>> seq[slice(0, 3, 1)] 'abc' ``` -This gives you the ability to work with slices in more creative ways in your code, since it allows you to assign a variable to a slice. +这将允许你在代码中做一些更加有意思的事情,因为你可以将变量赋值为切片对象。 ```python -# using the `slice` object to slice several sequences +# 使用 `slice` 对象来切片多个序列 >>> seq1 = "apple" >>> seq2 = (1, 2, 3, 4, 5) >>> seq3 = [True, False, None] @@ -398,59 +395,60 @@ This gives you the ability to work with slices in more creative ways in your cod
-**Takeaway**: +**经验**: -To "slice" a sequence is to retrieve a subsequence by specifying a start-index (included), a stop-index (excluded), and a step value. Negative values can be supplied for these, and default values are available as well. The common slicing syntax `seq[start:stop:step]` is actually just a nice shorthand for using a `slice` object: `seq[slice(start, stop, step)]`. +“切片”序列指通过指定起始索引(被包含),结尾索引(不被包含),和步距来获取子序列。你可以提供负值,也可以使用默认值。常见的 `seq[start:stop:step]` 语法其实就是使用 `slice` 对象的简写:`seq[slice(start, stop, step)]`。
-#### Handling out-of-bounds indices -Attempting to get a member from a sequence using an out-of-bounds index will raise an `IndexError`: +#### 处理超界索引 +试图使用某个超界的索引来获取序列成员会导致 `IndexError`: ```python ->>> x = [0, 1, 2, 3, 4, 5] # x only contains 6 items ->>> x[6] # try to access the 7th item in `x` +>>> x = [0, 1, 2, 3, 4, 5] # `x` 只有6个成员 +>>> x[6] # 试图获取 `x` 的第7个成员 IndexError: list index out of range >>> x[-7] IndexError: list index out of range ``` -However, specifying an out-of-bounds start or stop value for a slice does not raise an error. Instead, the nearest valid start/stop value is used instead: +但注意,在切片中提供超界的起始或结尾索引并不会导致错误。Python会使用最接近的合法起始或结尾值: + ```python -# no bounds checking is used for slicing +# 切片并不要求索引在界限内 >>> x[:10000] [0, 1, 2, 3, 4, 5] ```
-**Warning!** +**警告!** -The lack of bounds-checking for slices can be a major source of errors when starting out with Python. Just because your code isn't raising an error does not mean that you have computed the correct start/stop values for your slice! +入门Python时,切片不检查索引超界这一特征可能会成为一大错误源。代码不报错不代表你代码计算的起始和结尾索引就是正确的!
-**Reading Comprehension: Indexing and Slicing Sequences** +**阅读理解:索引和切片序列** -In Python, a **sequence** is any ordered collection of objects whose contents can be accessed via "indexing". A sub-sequence can be accessed by "slicing" the sequence. You saw, in the required reading, that Python's lists and strings are both examples of sequences. The following questions will help you explore the power of sequence indexing and slicing. +在Python中,**序列**(sequence)指任何包含对象的有序集合。你可以通过“索引”(indexing)来获取其中的成员,你也可以通过“切片”(slicing)来获取其中的子序列。你也在阅读本文时了解了Python的列表和字符串也都是序列这一事实。接下来的阅读理解题目将会帮助你探索序列索引和切片的强大性。 -Given the tuple: +设元组: ```python x = (0, 2, 4, 6, 8) ``` -Slice or index into `x` to produce the following: +对 `x` 切片或索引来获取以下: 1. `0` -2. `8` (using a negative index) -3. `(2, 4, 6)` (using a slice-object) +2. `8`(使用负索引) +3. `(2, 4, 6)`(使用切片) 4. `(4,)` -5. `4` -6. `4` (using a negative index) -7. `(6, 8)` (using a negative index for the start of the slice) +5. `4` +6. `4`(使用负索引) +7. `(6, 8)`(切片并使用负起始索引) 8. `(2, 6)` 9. `(8, 6, 4, 2)` @@ -459,38 +457,38 @@ Slice or index into `x` to produce the following:
-**Reading Comprehension: Checking Your General Understanding** +**阅读理解:检查你的理解** -Write a piece of code for each of the following tasks. If the task is impossible/ill-posed explain why. +为下列每个任务编写一组代码来完成它。如果你认为任务不可能或要求不合理,请解释为什么。 -1) Using the string "blogosphere", slicing, and repeat-concatenation, create the string: 'boopeeboopeeboopeeboopeeboopee'. (hint: how would you slice "blogosphere" to produce "boopee", think step-size) +1) 设字符串 "blogosphere",通过切片和多次粘连,创建字符串:'boopeeboopeeboopeeboopeeboopee'。(提示:你该如何切片 "blogosphere" 来获得 "boopee" 呢?步距。) -2) Assume that a tuple, `x`, contains the item `5` in it at least once. Find where that first entry is, and change it to `-5`. For example `(1, 2, 5, 0, 5)` $\rightarrow$ `(1, 2, -5, 0, 5)`. +2) 设包含对象 `5` 至少一次的元组 `x`。找出该对象第一次出现的位置,并将其修改成 `-5`。比如说,`(1, 2, 5, 0, 5)` $\rightarrow$ `(1, 2, -5, 0, 5)`。 -3) Given a sequence, `x`, and a valid negative index for `x`, `neg_index`, find the corresponding positive-value for that index. That is, if `x = "cat"`, and `neg_index = -3`, which is the negative index that would return `"c"`, then you would want to return the index `0`. +3) 设序列 `x` 和 `x` 的一个合法的负索引 `neg_index`,找出该索引对应的正值。比如说,如果 `x = "cat"`,`neg_index = -3`(也就是 `"c"` 的负索引),那你应该返回索引 `0`。
-## Links to Official Documentation +## 官方说明文档链接 -- [Sequences](https://docs.python.org/3/library/stdtypes.html#typesseq) -- [Tuples](https://docs.python.org/3/library/stdtypes.html#tuple) -- [Immutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types) -- [Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) +- [序列](https://docs.python.org/3/library/stdtypes.html#typesseq) +- [元组](https://docs.python.org/3/library/stdtypes.html#tuple) +- [不可变序列类](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types) +- [可变序列类](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**Basics of sequences** +**序列基础** ```python -# 1. Change the list [True, None, 22] into a tuple. +# 1. 将列表 `[True, None, 22]` 转化成元组 >>> tuple([True, None, 22]) (True, None, 22) ``` -2\. We have been introduced to three Python types that are sequential in nature: strings, lists, and tuples. Among these, lists are the only mutable objects. We can demonstrate this by simply appending a new element to the end of a list that has already been constructed. +2\. 我们介绍了三种序列性的Python类型:字符串,列表,和元组。在这其中,列表是唯一的可变对象。我们可以通过在一个已经创建的列表结尾附加新成员来演示它的可变性。 ```python >>> x = [1, 2, 3] >>> x @@ -503,7 +501,7 @@ Write a piece of code for each of the following tasks. If the task is impossible -**Indexing and Slicing Sequences: Solutions** +**索引和切片序列:解** 1. `x[0]` 2. `x[-1]` @@ -515,17 +513,17 @@ Write a piece of code for each of the following tasks. If the task is impossible 8. `x[1:4:2]` 9. `x[:0:-1]` -**Checking Your General Understanding: Solutions** +**检查你的理解:解** -1) "boopee" is every-other letter in "blogosphere", thus slicing this sequence with a step-size of 2, `"blogosphere"[::2]`, returns "boopee". We can then use `seq*n` to repeat this sequence five times. Thus the solution is +1) “boopee”也就是“blogosphere”的每两个字母,因此使用步距2来切片该序列,`"blogosphere"[::2]`,会返回“boopee”。我们可以使用 `seq*n` 来重复该序列5此。因此解是 ```python >>> "blogosphere"[::2]*5 'boopeeboopeeboopeeboopeeboopee' ``` -2) Tuples are immutable objects. This means that their content cannot be changed once it is created. Thus this question is ill-posed! How clever am I for writing that question? I feel so clever. Wow. I'm great. +2) 元组是不可变的。这意味着在创建后它们的内容是不可以被修改的,因此该任务不可能完成!写这个问题的我得有多聪明呢?我感觉自己贼聪明。哇,我真棒。 -If that question was posed in terms of a *list*, then the solution would be: +如果以上问题要求你修改一个*列表*,那解为: ```python >>> x = [1, 2, 5, 0, 5] >>> x[x.index(5)] = -5 @@ -533,7 +531,7 @@ If that question was posed in terms of a *list*, then the solution would be: [1, 2, -5, 0, 5] ``` -3) Refer to the "index" diagram to see that this is the simple relationship between positive and negative indices for a given sequence: +3) 查阅之前的索引图表来理解以下正索引和负索引的简单关系: ```python pos_index = neg_index + len(x) ``` diff --git a/Python/Module2_EssentialsOfPython/Variables_and_Assignment.md b/Python/Module2_EssentialsOfPython/Variables_and_Assignment.md index 9e31746..ef049ed 100644 --- a/Python/Module2_EssentialsOfPython/Variables_and_Assignment.md +++ b/Python/Module2_EssentialsOfPython/Variables_and_Assignment.md @@ -4,40 +4,40 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: variable naming and assignment, Difficulty: Medium, Category: Section :keywords: variable naming, valid names, mutable, immutable, reference, pointer -``` + -# Variables & Assignment +# 变量和赋值
-**Note**: +**注**: -There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page. +本文各处的阅读理解练习旨在帮助你练习使用文章中的知识点。练习题的答案可以在本页结尾找到。
-Variables permit us to write code that is flexible and amendable to repurpose. Suppose we want to write code that logs a student's grade on an exam. The logic behind this process should not depend on whether we are logging Brian's score of 92% versus Ashley's score of 94%. As such, we can utilize variables, say `name` and `grade`, to serve as placeholders for this information. In this subsection, we will demonstrate how to define variables in Python. +变量的意义在于帮助我们编写灵活易重用的代码。假设我们希望编写代码来记录学生的考试成绩,这过程背后的逻辑不管是记录小明的92分还是小丽的94分都应该是一样的。为此我们可以使用变量,如 `name` 和 `grade`,来作为这些信息的占位符。在本小节中,我们将会展示如何在Python中定义变量。 -In Python, the `=` symbol represents the "assignment" operator. The variable goes to the left of `=`, and the object that is being assigned to the variable goes to the right: +在Python中,符号 `=` 代表着“赋值”(assignment)操作符。变量在 `=` 左边,而用来赋值的对象在符号的右边: ```python -name = "Brian" # the variable `name` is being assigned the string "Brian" -grade = 92 # the variable `grade` is being assigned the integer 92 +name = "Brian" # 为变量 `name` 赋值字符串 "Brian" +grade = 92 # 为变量 `grade` 赋值整数 92 ``` -Attempting to reverse the assignment order (e.g. `92 = name`) will result in a syntax error. When a variable is assigned an object (like a number or a string), it is common to say that the variable **is a reference to** that object. For example, the variable `name` references the string `"Brian"`. This means that, once a variable is assigned an object, it can be used elsewhere in your code as a reference to (or placeholder for) that object: +将左右弄混(如 `92 = name`)会导致语法错误。当变量被某个对象(如一个数字或字符串)赋值时,我们经常会说这变量是该对象的*引用*(reference)。比如说,变量 `name` 是字符串 `"Brian"` 的引用。这意味着,当一个变量被对象赋值后,你可以在代码的其它地方将其作为该对象的代名词(或占位符)使用: ```python -# demonstrating the use of variables in code +# 演示使用变量 name = "Brian" grade = 92 failing = False @@ -45,59 +45,59 @@ failing = False if grade < 60: failing = True -# writes: name | grade | passing-status -# to the end of the file "student_grades.txt" +# 在文本文件“student_grades.txt”最后写: +# 名字 | 成绩 | 不及格 with open("student_grades.txt", mode="a") as opened_file: opened_file.write("{} | {} | {}".format(name, grade, failing)) ``` -## Valid Names for Variables -A variable name may consist of alphanumeric characters (`a-z`, `A-Z`, `0-9`) and the underscore symbol (`_`); a valid name cannot begin with a numerical value. +## 变量的合法名字 +合法的变量名字可以包括任何字母或数字(`a-z`,`A-Z`,`0-9`)以及下划线(`_`);合法的名字不可以由数字打头。 -- `var`: valid -- `_var2`: valid -- `ApplePie_Yum_Yum`: valid -- `2cool`: **invalid** (begins with a numerical character) -- `I.am.the.best`: **invalid** (contains `.`) +- `var`:合法 +- `_var2`:合法 +- `ApplePie_Yum_Yum`:合法 +- `2cool`:**不合法**(数字打头) +- `I.am.the.best`: **不合法**(包括了 `.`) -They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names: +变量名也不能和其它Python保留的特殊名字冲突。因此,下列名字也不能作为变量名: -- `for`, `while`, `break`, `pass`, `continue` -- `in`, `is`, `not` -- `if`, `else`, `elif` -- `def`, `class`, `return`, `yield`, `raises` -- `import`, `from`, `as`, `with` -- `try`, `except`, `finally` +- `for`,`while`,`break`,`pass`,`continue` +- `in`,`is`,`not` +- `if`,`else`,`elif` +- `def`,`class`,`return`,`yield`,`raises` +- `import`,`from`,`as`,`with` +- `try`,`except`,`finally` -There are other unicode characters that are permitted as valid characters in a Python variable name, but it is not worthwhile to delve into those details here. +还有一些unicode符号可以作为Python变量名中的字符,但本文在此不进行讨论。 -## Mutable and Immutable Objects -The **mutability** of an object refers to its ability to have its state changed. A **mutable object** can have its state changed, whereas an **immutable object** cannot. For instance, a list is an example of a mutable object. Once formed, we are able to update the contents of a list - replacing, adding to, and removing its elements. +## 可变和不可变对象 +对象的**可变性**指它的内态(state)是否能被改变。**可变对象**的内态可以被修改,而**不可变对象**则不能。比如说,列表就是可变对象的一种。在创建之后,我们可以更新列表的内容——代替,增加,或删除它的成员。 ```python -# demonstrating the mutability of a list +# 演示列表的可变性 >>> x = [1, 2, 3] ->>> x[0] = -4 # replace element-0 of `x` with -4 +>>> x[0] = -4 # 将 `x` 索引为0的成员修改成 -4 >>> x [-4, 2, 3] ``` -To spell out what is transpiring here, we: +让我们来看看这里具体发生了什么,我们: -1. Create (initialize) a list with the state `[1, 2, 3]`. -2. Assign this list to the variable `x`; `x` is now a reference to that list. -3. Using our referencing variable, `x`, update element-0 of the list to store the integer `-4`. +1. 创建(初始化)了一个列表,其内态为 `[1, 2, 3]`。 +2. 为变量 `x` 赋值了此列表;`x` 现在是该列表的一个引用了。 +3. 通过我们的引用变量 `x` 更新了列表索引为0的成员以储存整数 `-4`。 -This does not create a new list object, rather it *mutates* our original list. This is why printing `x` in the console displays `[-4, 2, 3]` and not `[1, 2, 3]`. +这并没有创建一个新的列表对象,而仅仅*修改*了原本的列表。这也是为什么在命令行中打印 `x` 会显示 `[-4, 2, 3]` 而不是 `[1, 2, 3]`。 -A tuple is an example of an immutable object. Once formed, there is no mechanism by which one can change of the state of a tuple; and any code that appears to be updating a tuple is in fact creating an entirely new tuple. +元组则是不可变对象的一种。在创建之后,我们没有任何办法可以改变元组的内态;任何看起来像是在更新元组的代码起始都是在创建一个全新的元组。 ```python -# demonstrating to the immutability of a tuple +# 演示元组的不可变性 >>> x = (1, 2, 3) ->>> x[0] = -4 # attempt to replace element-0 of `x` with -4 +>>> x[0] = -4 # 试图将 `x` 索引为0的成员修改为 -4 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -107,33 +107,32 @@ TypeError Traceback (most recent call last) TypeError: 'tuple' object does not support item assignment ``` -### Mutable & Immutable Types of Objects -The following are some common immutable and mutable objects in Python. These will be important to have in mind as we start to work with dictionaries and sets. +### 可变和不可变对象类型 +以下是Python中常见的一些可变和不可变对象。在我们开始讨论词典(dictionary)和集(set)时这些知识会很有用。 -**Some immutable objects** +**一些不可变对象** - - [numbers](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Number-Types) (integers, floating-point numbers, complex numbers) - - [strings](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Strings) - - [tuples](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Tuples) - - [booleans](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#The-Boolean-Type) - - ["frozen"-sets](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#The-%E2%80%9CSet%E2%80%9D-Data-Structure) + - [数字](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#数字类型)(整数,浮点数,复数) + - [字符串](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#字符串) + - [元组](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#元组) + - [布尔值](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#布尔类) + - ["冻结"集](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython%2FDataStructures_III_Sets_and_More.html#集数据结构)(frozen-set) -**Some mutable objects** +**一些可变对象** - - [lists](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Lists) - - [dictionaries](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html) - - [sets](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#The-%E2%80%9CSet%E2%80%9D-Data-Structure) - - [NumPy arrays](https://www.pythonlikeyoumeanit.com/module_3.html) + - [列表](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#列表) + - [词典](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html) + - [集](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_III_Sets_and_More.html#集数据结构) + - [NumPy数组](https://cn.pythonlikeyoumeanit.com/module_3.html) -## Referencing a Mutable Object with Multiple Variables -It is possible to assign variables to other, existing variables. Doing so will cause the variables to reference the same object: +## 多个变量引用一个可变对象 +你可以向变量赋值给其它已经存在的变量。这将会导致这些变量都引用同一个对象: ```python -# demonstrating the behavior of variables -# referencing the same object ->>> list1 = [1, 2, 3] # `list1` references [1, 2, 3] ->>> list2 = list1 # `list2` and `list1` now both reference [1, 2, 3] +# 演示引用同一个对象的变量行为 +>>> list1 = [1, 2, 3] # `list1` 引用 [1, 2, 3] +>>> list2 = list1 # `list2` 和 `list1` 现在都引用 [1, 2, 3] >>> print(list1) [1, 2, 3] @@ -142,56 +141,56 @@ It is possible to assign variables to other, existing variables. Doing so will c [1, 2, 3] ``` -What this entails is that these common variables will reference the *same instance* of the list. Meaning that if the list changes, all of the variables referencing that list will reflect this change: +具体来讲,这两个变量都引用这列表的*同一个实例*(instance)。这意味着如果列表有变化,所有引用它的变量都会反映这个变化: ```python ->>> list1.append(4) # append 4 to the end of [1, 2, 3] +>>> list1.append(4) # 在 [1, 2, 3] 结尾附加4 >>> print(list1) [1, 2, 3, 4] ``` -We can see that `list2` is still assigned to reference the *same, updated* list as `list1`: +我们可以看到 `list2` 还在引用*相同的,更新过的*列表,所以它和 `list1` 同步: ```python >>> print(list2) [1, 2, 3, 4] ``` -In general, assigning a variable `b` to a variable `a` will cause the variables to reference the *same* object in the system's memory, and assigning `c` to `a` or `b` will simply have a third variable reference this same object. Then any change (a.k.a *mutation*) of the object will be reflected in all of the variables that reference it (`a`, `b`, and `c`). +一般来讲,为变量 `b` 赋值变量 `a` 会导致它们引用系统内存中*相同*的对象,而为变量 `c` 赋值变量 `a` 或 `b` 会导致有第三个变量引用同样的对象。然后,该对象的任何变化(也就是*mutation*)会在所有引用它的变量中反映(`a`,`b`,和`c`)。 -Of course, assigning two variables to identical but *distinct* lists means that a change to one list will not affect the other: +当然,为两个变量赋值内容一样但*不同*的列表意味着一个列表的变化不会影响另外那个: ```python ->>> list1 = [1, 2, 3] # `list1` references [1, 2, 3] ->>> list2 = [1, 2, 3] # `list2` references a *separate* list, whose value is [1, 2, 3] +>>> list1 = [1, 2, 3] # `list1` 引用 [1, 2, 3] +>>> list2 = [1, 2, 3] # `list2` 引用*另外*一个列表,其值为 [1, 2, 3] ->>> list1.append(4) # append 4 to the end of [1, 2, 3] +>>> list1.append(4) # 在 [1, 2, 3] 结尾附加4 >>> print(list1) [1, 2, 3, 4] ->>> print(list2) # `list2` still references its own list +>>> print(list2) # `list2` 依然引用它自己的列表 [1, 2, 3] ```
-**Reading Comprehension: Does slicing a list produce a reference to that list?** +**阅读理解:切片列表是否会创建一个列表的引用?** -Suppose `x` is assigned a list, and that `y` is assigned a "slice" of `x`. Do `x` and `y` reference the same list? That is, if you update part of the subsequence common to `x` and `y`, does that change show up in both of them? Write some simple code to investigate this. +设变量 `x`,赋值为一个列表,和变量 `y`,赋值为 `x` 的一个“切片”。`x` 和 `y` 是否引用同样的列表?也就是说,当你更新 `x` 和 `y` 的子序列时,变化是否会在两个变量中都显示?请编写一些简单的代码来查明此问题。
-**Reading Comprehension: Understanding References** +**阅读理解:理解引用** -Based on our discussion of mutable and immutable objects, predict what the value of `y` will be in the following circumstance: +根据我们对可变和不可变对象的讨论,预测下列情况中 `y` 的最终值: ```python >>> x = 3 >>> y = x -# shorthand for: `x = x * 3` +# 和 `x = x * 3` 等值 >>> x *= 3 >>> x 9 @@ -204,27 +203,27 @@ Based on our discussion of mutable and immutable objects, predict what the value -## Reading Comprehension Exercise Solutions: +## 阅读理解答案 -**Does slicing a list produce a reference to that list?: Solution** +**切片列表是否会创建一个列表的引用?:解** -Based on the following behavior, we can conclude that slicing a list does **not** produce a reference to the original list. Rather, slicing a list produces a copy of the appropriate subsequence of the list: +根据以下的行为,我们可以得出切片列表*并不*创建一个列表的新引用。反而,切片列表会创建对应列表子序列的新列表: ```python >>> x = [0, 1, 2, 3] >>> y = x[:2] ->>> y # does `y` reference the same list as `x`? +>>> y # `y` 是否和 `x` 引用同一个列表? [0, 1] ->>> x[0] = -1 # update one of the entries of the list that `x` references +>>> x[0] = -1 # 更新 `x` 引用的列表中的某个成员 >>> x [-1, 1, 2, 3] ->>> y # the list that `y` references was unaffected by the update +>>> y # `y` 引用的列表并没有反映这个更新 [0, 1] ``` -**Understanding References: Solutions** +**理解引用:解** -Integers are immutable, thus `x` must reference an entirely new object (`9`), and `y` still references `3`. +整数不可变,因此 `x` 肯定是引用一个全新的对象(`9`),而 `y` 还在引用 `3`。 diff --git a/Python/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.md b/Python/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.md index 85f78fe..5d52fd9 100644 --- a/Python/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.md +++ b/Python/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.md @@ -4,43 +4,43 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Indexing into multi-dimensional numpy arrays, Difficulty: Easy, Category: Section :keywords: numpy array, multidimensional, index, slice, negative index, rows, columns -``` + -# Accessing Data Along Multiple Dimensions in an Array -In this section, we will: +# 访问数组多维度的内容 +在本节中,我们将会: + + - 定义数组的“维度”(dimensionality)。 + - 讨论N维数组(ND-array)的作用。 + - 介绍访问多维数组内容的索引和切片体系。 - - Define the "dimensionality" of an array. - - Discuss the usefulness of ND-arrays. - - Introduce the indexing and slicing scheme for accessing a multi-dimensional array's contents - -We will encounter arrays of varying dimensionalities: +我们将会遇到不同维度的数组: ```python -# A 0-D array +# 0维数组 np.array(8) -# A 1-D array, shape-(3,) +# 1维数组,形状为 (3,) np.array([2.3, 0.1, -9.1]) -# A 2-D array, shape-(3, 2) +# 2维数组,形状为 (3, 2) np.array([[93, 95], [84, 100], [99, 87]]) -# A 3-D array, shape-(2, 2, 2) +# 3维数组,形状为 (2, 2, 2) np.array([[[0, 1], [2, 3]], @@ -48,18 +48,18 @@ np.array([[[0, 1], [6, 7]]]) ``` -Similar to Python's sequences, we use 0-based indices and slicing to access the content of an array. However, we must specify an index/slice for *each* dimension of an array: +和Python的序列类似,我们使用0开始的索引和切片来获取数组中的内容。但是,我们必须为数组的*每个*维度提供索引/切片: ```python >>> import numpy as np -# A 3-D array +# 3维数组 >>> x = np.array([[[0, 1], ... [2, 3]], ... ... [[4, 5], ... [6, 7]]]) -# get: sheet-0, both rows, flip order of columns +# 获取:第0页,全部两行,反向排列的列 >>> x[0, :, ::-1] array([[1, 0], [3, 2]]) @@ -67,13 +67,13 @@ array([[1, 0], -## One-dimensional Arrays -Let's begin our discussion by constructing a simple ND-array containing three floating-point numbers. +## 一维数组 +让我们首先创建一额简单的N维数组,其成员为三个浮点数。 ```python >>> simple_array = np.array([2.3, 0.1, -9.1]) ``` -This array supports the same indexing scheme as Python's sequences (lists, tuples, and strings): +这个数组支持和Python序列(列表,元组,和字符串)一样的索引体系: ``` +------+------+------+ @@ -82,7 +82,7 @@ This array supports the same indexing scheme as Python's sequences (lists, tuple 0 1 2 -3 -2 -1 ``` -The first row of numbers gives the position of the indices 0…3 in the array; the second row gives the corresponding negative indices. The slice from $i$ to $j$ returns an array containing of all numbers between the edges labeled $i$ and $j$, respectively: +第一行数字提供了索引0-2在数组中对应的位置;第二行则提供了对应的负索引。从 $i$ 到 $j$ 的切片将返回一个在标记索引为 $i$ 和 $j$ 的成员之间所有的值(包括 $i$ 但不包括 $j$): ```python >>> simple_array[0] @@ -98,56 +98,56 @@ array([ 0.1, -9.1]) IndexError: index 3 is out of bounds for axis 0 with size 3 ``` -Given this indexing scheme, only *one* integer is needed to specify a unique entry in the array. Similarly only *one* slice is needed to uniquely specify a subsequence of entries in the array. For this reason, we say that this is a *1-dimensional array*. In general, the *dimensionality* of an array specifies the number of indices that are required to uniquely specify one of its entries. +根据以上的索引体系,你只需要*一个*整数就能无歧义地辨别数组中的一个成员。相应的,你只需要*一个*切片就能无歧义地辨别数组中的一个子序列。因此,我们称其为*一维数组*(1-dimensional array)。笼统来讲,数组的*维度*(dimensionality)描述了无歧义辨别数组中单个成员所需要的索引数量。
-**Definition**: +**定义**: -The **dimensionality** of an array specifies the number of indices that are required to uniquely specify one of its entries. +数组的**维度**(dimensionality)指无歧义地辨别其单个成员所需要的索引数量。
-This definition of dimensionality is common far beyond NumPy; one must use three numbers to uniquely specify a point in physical space, which is why it is said that space consists of three dimensions. +这个维度的定义在NumPy之外也通用;你需要三个数字来无歧义地描述现实空间中的一个点,所以我们认为空间有着三个维度。 -## Two-dimensional Arrays -Before proceeding further down the path of high-dimensional arrays, let's briefly consider a very simple dataset where the desire to access the data along multiple dimensions is manifestly desirable. Consider the following table from a gradebook: +## 二维数组 +在我们开始讨论高维数组之前,让我们先讨论一个很简单的需要在多维度获取数据的数据集。某成绩簿有着以下表格: -| | Exam 1 (%) | Exam 2 (%) | +| | 考试1 (%) | 考试2 (%) | | ------------- |:-------------:| -----:| | Ashley | $93$ | $95$ | | Brad | $84$ | $100$ | | Cassie | $99$ | $87$ | -This dataset contains 6 grade-values. It is almost immediately clear that storing these in a 1-dimensional array is not ideal: +这个数据集总共有6个成绩值。将其存为一维数组明显是不智的: ```python -# using a 1-dimensional array to store the grades +# 使用1维数组来储存成绩 >>> grades = np.array([93, 95, 84, 100, 99, 87]) ``` -While no data has been lost, accessing this data using a single index is less than convenient; we want to be able to specify both the student and the exam when accessing a grade - it is natural to ascribe *two dimensions* to this data. Let's construct a 2D array containing these grades: +虽然我们没有丢失任何数据,但是使用单个索引来访问其中的数据很不方便;我们希望能在获取成绩时提供学生和需要的考试——所以说使用*两个维度*来储存这些数据是再自然不过的。让我们创建一个存储这些成绩的二维数组: ```python -# using a 2-dimensional array to store the grades +# 使用2维数组来储存成绩 >>> grades = np.array([[93, 95], ... [84, 100], ... [99, 87]]) ``` -NumPy is able to see the repeated structure among the list-of-lists-of-numbers passed to `np.array`, and resolve the two dimensions of data, which we deem the 'student' dimension and the 'exam' dimension, respectively. +NumPy能够处理向 `np.array` 输入的成员为列表的列表,并根据其重复结构将其存为一个二维数组,第一维为“学生”维度,第二维度为“考试”维度。
-**Axis vs Dimension**: +**轴心 vs 维度**: -Although NumPy does formally recognize the concept of dimensionality precisely in the way that it is discussed here, its documentation refers to an individual dimension of an array as an **axis**. Thus you will see "axes" (pronounced "aks-ēz") used in place of "dimensions"; however, they mean the same thing. +虽然NumPy正式承认维度这一概念且对其进行了和本节一样的定义,但是它的说明文档将数组的单个维度称为一个**轴**(axis,复数为axes)。因此你有时会见到说明文档用“axes”代替“dimensions”;但是,它们指着同样的东西。
-NumPy specifies the row-axis (students) of a 2D array as "axis-0" and the column-axis (exams) as axis-1. You must now provide *two* indices, one for each axis (dimension), to uniquely specify an element in this 2D array; the first number specifies an index along axis-0, the second specifies an index along axis-1. The zero-based indexing schema that we reviewed earlier applies to each axis of the ND-array: +NumPy将二维数组的行轴(学生)称为“轴0”,列轴(exams)称为“轴1”。你必须提供“两个”索引(每个轴心(维度)各一个)来无歧义地辨别这个二维数组中的一个成员;第一个数字提供了在轴0上的索引,第二个数字提供了在轴1上的索引。不管是哪个轴心,我们之前复习的从0开始的索引体系都通用: ``` -- axis-1 -> @@ -162,98 +162,97 @@ NumPy specifies the row-axis (students) of a 2D array as "axis-0" and the column V +---+---+ ``` -Because `grades` has three entries along axis-0 and two entries along axis-1, it has a "shape" of `(3, 2)`. +因为 `grades` 在轴0上有三行数据,在轴1上由两行数据,它的“形状”(shape)为 `(3, 2)`。 ```python >>> grades.shape (3, 2) ``` -### Integer Indexing -Thus, if we want to access Brad's (item-1 along axis-0) score for Exam 1 (item-0 along axis-1) we simply specify: +### 整数索引 +因此,如果我们想要获取Brad(轴0上的项目1)的考试1(轴1上的项目0)的成绩,我们只需要提供: ```python -# providing two numbers to access an element -# in a 2D-array ->>> grades[1, 0] # Brad's score on Exam 1 +# 提供两个数字来访问2维数组的成员 +>>> grades[1, 0] # Brad考试1的成绩 84 -# negative indices work as with lists/tuples/strings ->>> grades[-2, 0] # Brad's score on Exam 1 +# 负索引和列表/元组/字符串一样可以使用 +>>> grades[-2, 0] # Brad考试1的成绩 84 ``` -### Slice Indexing -We can also uses *slices* to access subsequences of our data. Suppose we want the scores of all the students for Exam 2. We can slice from 0 through 3 along axis-0 (refer to the indexing diagram in the previous section) to include all the students, and specify index 1 on axis-1 to select Exam 2: +### 切片索引 +我们也可以使用*切片*(slice)来获取数据的子序列。假设我们想要获取所有成绩在考试2的成绩,我们可以在轴0上从0到3切片(请参考之前小节的索引图)来包含所有学生,并在轴1上提供索引1来选中考试2: ```python ->>> grades[0:3, 1] # Exam 2 scores for all students +>>> grades[0:3, 1] # 所有学生的考试2成绩 array([ 95, 100, 87]) ``` -As with Python sequences, you can specify an "empty" slice to include all possible entries along an axis, by default: `grades[:, 1]` is equivalent to `grades[0:3, 1]`, in this instance. More generally, withholding either the 'start' or 'stop' value in a slice will result in the use smallest or largest valid index, respectively: +和Python序列一样,你可以提供一个“空”切片来默认包含某轴的所有项目:在这个序列中 `grades[:, 1]` 等值于 `grades[0:3, 1]`。更笼统的来讲,跳过不填切片的 'start' 或 'stop' 值会分别默认使用最小或最大的合法索引: ```python ->>> grades[1:, 1] # equivalent to `grades[1:3, 1] +>>> grades[1:, 1] # 等值于 `grades[1:3, 1]` array([ 100, 87]) ->>> grades[:, :1] # equivalent to `grades[0:3, 0:1] +>>> grades[:, :1] # 等值于 `grades[0:3, 0:1]` array([[93], [84], [99]]) ``` -The output of `grades[:, :1]` might look somewhat funny. Because the axis-1 slice only includes one column of numbers, the shape of the resulting array is (3, 1). 0 is thus only valid (non-negative) index for axis-1, since there is only one column to specify in the array. +`grades[:, :1]` 的输出可能看起来有点奇怪。因为轴1切片仅仅包含了一列的数字,最后得到的数组的形状为 (3, 1)。所以,在轴1上0是唯一的合法(非负)索引,因为在这个得到的数组中只有一行可以选中。 -You can also supply a "step" value to the slice. `grades[::-1, :]` will returns the array of grades with the student-axis flipped (reverse-alphabetical order). +你也可以为切片提供一个“step”(步距)值。`grades[::-1, :]` 会返回学生轴颠倒的成绩数组。 -### Negative Indices -As indicated above, negative indices are valid too and are quite useful. If we want to access the scores of the latest exam for all of the students, you can specify: +### 负索引 +如上所述,负索引也合法,且很有用。如果我们想要访问所有学生最新的考试成绩,我们可以编写: ```python -# using a negative index and a slice ->>> grades[:, -1] # Latest exam scores (Exam 2), for all students +# 使用负索引和切片 +>>> grades[:, -1] # 所有学生的最新考试成绩(考试2) array([ 95, 100, 87]) ``` -Note the value of using the negative index is that it will always provide you with the latest exam score - you need not check how many exams the students have taken. +请注意使用负索引的价值在于它永远都会为你提供最新的考试成绩——你不需要先检查学生考过多少次。 -### Supplying Fewer Indices Than Dimensions -What happens if we only supply one index to our array? It may be surprising that `grades[0]` does not throw an error since we are specifying only one index to access data from a 2-dimensional array. Instead, NumPy it will return all of the exam scores for student-0 (Ashley): +### 提供低于维度数量的索引 +在我们为这个数组只提供一个索引时会发生什么?你可能会惊讶于 `grades[0]` 并不会报错这一事,因为我们为二维数组只提供了一个索引。反而,NumPy将会返回学生0(Ashley)的所有考试成绩: ```python >>> grades[0] array([ 93, 95]) ``` -This is because NumPy will automatically insert trailing slices for you if you don't provide as many indices as there are dimensions for your array. `grades[0]` was treated as `grades[0, :]`. +这是因为NumPy会在你不提供足够多的索引时自动在结尾提供缺失的切片。`grades[0]` 会被当作 `grades[0, :]` 处理。
-Suppose you have an $N$-dimensional array, and only provide $j$ indices for the array; NumPy will automatically insert $N-j$ trailing slices for you. In the case that $N=5$ and $j=3$, `d5_array[0, 0, 0]` is treated as `d5_array[0, 0, 0, :, :]` +假设你有着一个 $N$ 维数组并在索引时仅仅提供了 $j$ 个索引;NumPy将会在结尾自动插入 $N-j$ 个切片。如果 $N=5$,$j=3$,那么 `d5_array[0, 0, 0]` 等值于 `d5_array[0, 0, 0, :, :]`。
-Thus far, we have discussed some rules for accessing data in arrays, all of which fall into the category that is designated ["basic indexing"](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing) by the NumPy documentation. We will discuss the details of basic indexing and of ["advanced indexing"](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing), in full, in a later section. Note, however, that all of the indexing/slicing reviewed here produces a "view" of the original array. That is, *no data is copied* when you index into an array using integer indices and/or slices. Recall that slicing lists and tuples *do* produce copies of the data. +到现在为止,我们讨论了一些在数组中获取数据的规则,但这些规则都属于NumPy说明文档规定为[“基础索引”](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing)(basic indexing)的一部分。我们将在之后一节完整地讨论基础索引和[“进阶索引”](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing)(advanced indexing)。但是,请注意,在这里复习的所有索引/切片方法都会创建原本数组的一个“视阈“(view)。也就是说,当你使用整数索引或切片索引数组时,*没有任何数据被复制*。请回忆,切片列表和元组*会*复制其数据。
-**FYI**: +**供参考**: -Keeping track of the meaning of an array's various dimensions can quickly become unwieldy when working with real datasets. [xarray](http://xarray.pydata.org/en/stable/) is a Python library that provides functionality comparable to NumPy, but allows users provide *explicit labels* for an array's dimensions; that is, you can *name* each dimension. Using an `xarray` to select Brad's scores could look like `grades.sel(student='Brad')`, for instance. This is a valuable library to look into at your leisure. +记录数组每个维度的含义可能在处理现实中的数据集时很快变得麻烦复杂。[xarray](http://xarray.pydata.org/en/stable/)则是一个提供和NumPy相似功能的,但允许用户为数组的维度提供*显式标签*的Python模组。也就是说,你可以为每个维度*命名*。比如说,你可以如下使用 `xarray` 来选中Brad的成绩:`grades.sel(student='Brad')`。在你有空的时候,这是一个值得花些时间去了解的模组。
-## N-dimensional Arrays -Let's build up some intuition for arrays with a dimensionality higher than 2. The following code creates a 3-dimensional array: +## N维数组 +让我们对维度高于2的数组产生一些直观的理解。以下代码创建一个三维数组: ```python -# a 3D array, shape-(2, 2, 2) +# 三维数组,形状为 (2, 2, 2) >>> d3_array = np.array([[[0, 1], ... [2, 3]], ... ... [[4, 5], ... [6, 7]]]) ``` -You can think of axis-0 denoting which of the 2x2 "sheets" to select from. Then axis-1 specifies the row along the sheets, and axis-2 the column within the row: +你可以认为轴0代表着选中哪个2x2的“页”(sheet),然后轴1代表着在页中选中哪一行,而轴2代表着在行中选择哪个列: -**Depicting the layout of a 3D array** +**描绘3维数组的结构** ``` sheet 0: [0, 1] @@ -278,28 +277,28 @@ You can think of axis-0 denoting which of the 2x2 "sheets" to select from. Then ``` -Thus `d3_array[0, 1, 0]` specifies the element residing in sheet-0, at row-1 and column-0: +如此,`d3_array[0, 1, 0]` 选中了在页0,行1,列0的成员: ```python -# retrieving a single element from a 3D-array +# 在3维数组中获得单个成员 >>> d3_array[0, 1, 0] 2 ``` -`d3_array[:, 0, 0]` specifies the elements in row-0 and column-0 of **both** sheets: +`d3_array[:, 0, 0]` 选中了**全部**页在行0和列0的成员: ```python -# retrieving a 1D sub-array from a 3D-array +# 在3维数组中获得1维子数组 >>> d3_array[:, 0, 0] array([0, 4]) ``` -`d3_array[1]`, which recall is shorthand for `d3_array[1, :, :]`, selects both rows and both columns of sheet-1: +`d3_array[1]`,也就是 `d3_array[1, :, :]` 的简写,选中页1全部的行和列: ```python -# retrieving a 2D sub-array from a 3D-array +# 在3维数组中获得2维子数组 >>> d3_array[1] array([[4, 5], [6, 7]]) ``` -In four dimensions, one can think of "*stacks* of sheets with rows and columns" where axis-0 selects the stack of sheets you are working with, axis-1 chooses the sheet, axis-2 chooses the row, and axis-3 chooses the column. Extrapolating to higher dimensions ("collections of stacks of sheets ...") continues in the same tedious fashion. +在四维的情况下,你可以将轴0的成员理解为“一*打*(stack)有着行列的页”。轴0选中哪一打页,轴1选中哪一页,轴2选中哪一行,轴3选中哪一列。往更高维度扩展这个类比(“好多打页的集合”)将像这个相同的冗长的方式继续。 @@ -308,9 +307,9 @@ In four dimensions, one can think of "*stacks* of sheets with rows and columns"
-**Reading Comprehension: Multi-dimensional Indexing** +**阅读理解:多维索引** -Given the 3D, shape-(3, 3, 3) array: +设3维数组,其形状为 (3, 3, 3): ```python >>> arr = np.array([[[ 0, 1, 2], @@ -326,7 +325,7 @@ Given the 3D, shape-(3, 3, 3) array: ... [24, 25, 26]]]) ``` -Index into the array to produce the following results +索引该数组来得到以下结果 ```python #1 @@ -351,16 +350,16 @@ array([[11, 10, 9], -## Zero-dimensional Arrays -A zero dimensional array is simply a single number (a.k.a. a scalar value): +## 零维数组 +零维数组仅仅是一个数字(也就是一个标量值): ```python -# creating a 0-dimensional array +# 创建一个0维数组 >>> x = np.array(15.2) ``` -This is *not* equivalent to a length-1 1D-array: `np.array([15.2])`. According to our definition of dimensionality, *zero* numbers are required to index into a 0-D array as it is unnecessary to provide an identifier for a standalone number. Thus you cannot index into a 0-D array. +这*不*等值于长度为1的一维数组:`np.array([15.2])`。根据维度的定义,我们需要*零*个数字来索引一个0维数组,因为我们不需要为单个数字其提供任何索引。因此,你不能索引0维数组。 ```python -# you cannot index into a 0-D array +# 你不能索引0维数组 >>> x[0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) @@ -371,33 +370,33 @@ IndexError: too many indices for array ``` -You must use the syntax `arr.item()` to retrieve the numerical entry from a 0D array: +你必须使用语法 `arr.item()` 来获取0维数组的数字值: ```python >>> x.item() 15.2 ``` -Zero-dimensional arrays do not show up in real applications very often. They are, however, important from the point of view of NumPy being self-consistent in how it treats dimensionality in its arrays, and it is important that you are at least exposed to a 0D array and understand its nuances. +零维数组在实际使用时不会经常出现。但是,它们的行为证明了NumPy对其数组维度的定义是自治的,而你也应该至少接触以下并理解0维数组的细节。
-**Takeaway**: +**经验**: -Although accessing data along varying dimensions is ultimately all a matter of judicious bookkeeping (you *could* access all of this data from a 1-dimensional array, after all), NumPy's ability to provide users with an interface for accessing data along dimensions is incredibly useful. It affords us an ability to impose intuitive, abstract structure to our data. +虽然在多个维度访问数据最终其实也就是一个细心活(因为你理论上*可以*通过一个一维数组来访问同样的数据),但是NumPy为用户提供的多维度访问数组内容的界面是非常有用的。它为我们提供了给数据赋予直观的抽象结构的能力。
-## Manipulating Arrays -NumPy provides an assortment of functions that allow us manipulate the way that an array's data can be accessed. These permit us to reshape an array, change its dimensionality, and swap the positions of its axes: +## 操作数组 +NumPy提供了一系列操作如何访问数组数据的方法。这些函数能让我们重塑(reshape)数组的形状,修改它的维度,并交换它不同轴的位置: ```python >>> x = np.array([[ 1, 2, 3, 4], ... [ 5, 6, 7, 8], ... [ 9, 10, 11, 12]]) -# reshaping an array +# 重塑数组形状 >>> x.reshape(3, 2, 2) array([[[ 1, 2], [ 3, 4]], @@ -408,53 +407,51 @@ array([[[ 1, 2], [[ 9, 10], [11, 12]]]) -# Transposing an array: reversing -# the ordering of its axes. This interchanges -# the rows and columns of `x` +# 转制(transpose)数组:交换数组轴的顺序。 +# 这将 `x` 的行列互换 >>> x.transpose() array([[ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11], [ 4, 8, 12]]) ``` -A complete listing of the available array-manipulation functions can be found in the [official NumPy documentation](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html). Among these functions, the reshape function is especially useful. +完整的数组操作函数列表可以在[NumPy的官方说明文档](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html)找到。在这些函数中,reshape函数极其有用。 -### Introducing the `reshape` Function -The `reshape` function allows you to change the dimensionality and axis-layout of a given array. This adjusts the indexing interface used to access the array's underlying data, as was discussed in earlier in this module. Let's take a shape-(6,) array, and reshape it to a shape-(2, 3) array: +### 介绍 `reshape` 函数 +`reshape` 函数允许你修改数组的维度和轴结构。它修改用来访问数组内置数据的本模组之前讨论过的索引界面。设一个形状为 (6,) 的数组,让我们将其重塑成形为 (2, 3) 的数组: ```python >>> import numpy as np >>> x = np.array([0, 1, 2, 3, 4, 5]) -# reshape a shape-(6,) array into a shape-(2,3) array +# 将形状为 (6,) 的数组重塑为形状为 (2,3) 的数组 >>> x.reshape(2, 3) array([[0, 1, 2], [3, 4, 5]]) ``` -You can also conveniently reshape an array by "setting" its shape via assignment: +你也可以很方便地通过在赋值时“设置”它的形状来达到重塑的目的: ```python # equivalent to: x = x.reshape(2, 3) >>> x.shape = (2, 3) ``` -Of course, the size the the initial array must match the size of the to-be reshaped array: +当然,最初数组的大小要对应重塑后的数组的大小: ```python -# an array with 5 numbers are cannot be reshaped -# into a (3, 2) array +# 一个有5个数字的数组不能被重塑为形状是 (3, 2) 的数组 >>> np.array([0, 1, 2, 3, 4]).reshape(3, 2) ValueError: total size of new array must be unchanged ``` -Multidimensional arrays can be reshaped too: +多维数组也可以被重塑: ```python -# reshaping a multidimensional array +# 重塑多维数组的形状 >>> x = np.array([[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]]) -# reshape from (3, 4) to (2, 3, 2) +# 从 (3, 4) 重塑为 (2, 3, 2) >>> x.reshape(2, 3, 2) array([[[ 0, 1], [ 2, 3], @@ -465,19 +462,19 @@ array([[[ 0, 1], [10, 11]]]) ``` -Because the size of an input array and the resulting reshaped array must agree, you can specify *one* of the dimension-sizes in the reshape function to be -1, and this will cue NumPy to compute that dimension's size for you. For example, if you are reshaping a shape-(36,) array into a shape-(3, 4, 3) array. The following are valid: +因为输入数组的大小和重塑数组的大小必须相同,你可以在reshape函数中将维度大小之中的*一个*设置为-1.这将告诉NumPy去为你计算该维度的大小。比如说,如果你在将形状 (36,) 的数组重塑为形状是 (3, 4, 3) 的数组,以下都可以: ```python -# Equivalent ways of specifying a reshape -# np.arange(36) produces the shape-(36,) array ([0, 1, 2, ..., 35]) -np.arange(36).reshape(3, 4, 3) # (36,) --reshape--> (3, 4, 3) -np.arange(36).reshape(3, 4, -1) # NumPy replaces -1 with 36/(3*4) -> 3 -np.arange(36).reshape(3, -1, 3) # NumPy replaces -1 with 36/(3*3) -> 4 -np.arange(36).reshape(-1, 4, 3) # NumPy replaces -1 with 36/(3*4) -> 3 +# 等值的重塑方法 +# np.arange(36) 返回一个形状为 (36,) 的数组([0, 1, 2, ..., 35]) +np.arange(36).reshape(3, 4, 3) # (36,) --重塑--> (3, 4, 3) +np.arange(36).reshape(3, 4, -1) # NumPy 将 -1 代替为 36/(3*4) -> 3 +np.arange(36).reshape(3, -1, 3) # NumPy 将 -1 代替为 36/(3*3) -> 4 +np.arange(36).reshape(-1, 4, 3) # NumPy 将 -1 代替为 36/(3*4) -> 3 ``` -You can use -1 to specify only one dimension: +你只能用-1来描述一个维度: ```python ->>> np.arange(36).reshape(3, -1, -1) # this is an ambiguous specification, and thus +>>> np.arange(36).reshape(3, -1, -1) # 这可能有歧义,所以... --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -488,26 +485,26 @@ ValueError: can only specify one unknown dimension
-**Reshaping Does Not Make a Copy of an Array**: +**重塑并不会复制数组**: -For all straightforward applications of reshape, NumPy does not actually create a new copy of an array's data when performing a `reshape` operation. Instead, the original array and the reshaped array reference the same underlying data. The reshaped array simply provides a new index-interface for accessing said data, and is thus referred to as a "view" of the original array (more on this "views" in a later section). +任何直接运用reshape的情况下,NumPy都不会复制原本数组数据。实际上,原本的数组和重塑的数组都引用着相同的内在数据。重塑的数组仅仅提供了一个新的访问该数据的索引界面,所以它被是原本数组的一个“视阈”(view)(我们会在后面一节详细讨论“视阈”)。
-## Links to Official Documentation +## 官方说明文档链接 -- [The N-dimensional array](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) -- [Array indexing](https://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing) -- [Indexing routines](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#indexing-routines) -- [Array manipulation routines](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html) +- [N维数组](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) +- [数组索引](https://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing) +- [索引常规](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#indexing-routines) +- [数组操作常规](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html) -## Reading Comprehension Solutions +## 阅读理解答案: -**Reading Comprehension: Multi-dimensional Indexing** +**阅读理解:多维索引** ```python >>> arr = np.array([[[ 0, 1, 2], diff --git a/Python/Module3_IntroducingNumpy/AdvancedIndexing.md b/Python/Module3_IntroducingNumpy/AdvancedIndexing.md index cc91851..2997206 100644 --- a/Python/Module3_IntroducingNumpy/AdvancedIndexing.md +++ b/Python/Module3_IntroducingNumpy/AdvancedIndexing.md @@ -4,24 +4,24 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Advanced indexing with numpy arrays, Difficulty: Hard, Category: Section :keywords: numpy array, integer array indexing, boolean array indexing, copy indexing, advanced -``` + -# Advanced Indexing +# 进阶索引 -We conclude our discussion of indexing into N-dimensional NumPy arrays by understanding advanced indexing. Unlike basic indexing, which allows us to access distinct elements and regular slices of an array, advanced indexing is significantly more flexible. For example, arrays of integers can be used to access arbitrary and even repeated entries from an array, +我们将通过理解进阶索引来为我们对索引N维NumPy数组的讨论收尾。和允许我们访问数组单个成员和规则切片的基础索引不同,进阶索引相比灵活很多。比如说,我们可以使用整数数组来作为索引访问数组任意多甚至重复的成员: ```python >>> import numpy as np @@ -30,8 +30,7 @@ We conclude our discussion of indexing into N-dimensional NumPy arrays by unders ... [3, 4, 5], ... [6, 7, 8]]) -# Construct the following 2D array -# from the contents of `x`: +# 利用 `x` 的成员来创建以下2维数组: # # [[x[0, 0], x[0, 1]], # [x[2, 2], x[2, 2]]] @@ -46,14 +45,12 @@ array([[0, 1], [8, 8]]) ``` -Additionally, it permits the use of *boolean-valued* arrays as indices, +同时,它允许我们使用*布尔值*数组来作为索引: ```python -# Use a boolean-valued array to access -# the diagonal values of an array +# 使用布尔值数组来访问数组对角线的值 -# Specify `True` wherever we want to access -# the entry of `x` +# 在我们想要访问的 `x` 的成员的位置提供 `True` >>> bool_index = np.array([[ True, False, False], ... [False, True, False], ... [False, False, True]]) @@ -62,7 +59,7 @@ Additionally, it permits the use of *boolean-valued* arrays as indices, array([0, 4, 8]) ``` -Unlike basic indexing, advanced indexing always produces a copy of the underlying data. +和基础索引不同,进阶索引永远都会返回内置数据的复制品。 ```python >>> np.shares_memory(x, x[rows, cols]) False @@ -70,36 +67,36 @@ False >>> np.shares_memory(x, x[bool_index]) False ``` -The flexibility permitted by advanced indexing makes it a difficult topic to treat exhaustively without delving into somewhat terse and abstract notation. It is best to refer to [the official documentation](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing) for such a treatment of the topic. Here, we will discuss the essential aspects of advanced indexing, with the aim of the discussion being both thorough and accessible. +进阶索引提供的灵活性使得它很难在不深入理解一些抽象极短的符号的情况下完整地讨论。如果读者想要一个追求完整性的讨论,请参阅[官方说明文档](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing)。在这里,我们将会尽可能平衡深入性和易读性地讨论进阶索引的核心功能。
-**Advanced Indexing**: +**进阶索引**: -Given an $N$-dimensional array, `x`, `x[index]` invokes **advanced indexing** whenever `index` is: +设 $N$ 维数组 `x`,当 `index` 为以下之一时,`x[index]` 使用**进阶索引**(advanced indexing): -- an integer-type or boolean-type `numpy.ndarray` -- a `tuple` with at least one *sequence*-type object as an element (e.g. a list, tuple, or ndarray) +- 整数或布尔类的 `numpy.ndarray` +- 一个至少有着一个*序列*类型对象(比如说列表,元组,或ndarray)成员的 `tuple` -Accessing the contents of an array via advanced indexing *always returns a copy of those contents*, whereas basic indexing returns a view. +通过进阶索引访问这些成员**永远都会返回数据的复制品*,而基础索引返回一个视阈。
-## Integer Array Indexing +## 整数数组索引 -### Indexing into 1-Dimensional Arrays -Using an integer-type array as an index allows us to access the contents of an array arbitrarily, permitting items to be accessed out of order, and even repeatedly. Consider the following 1-dimensional array. +### 索引一维数组 +使用整数数组作为索引允许我们任意——无序甚至重复地——访问数组成员。设以下1维数组: ```python y = np.array([ 0, -1, -2, -3, -4, -5]) ``` -See that we can access an arbitrary number of the array's contents in an unpatterned way, which is not permissible via basic index: +我们可以无规律地访问任意多的数组成员;这在使用基础索引时是不允许的: ```python -# advanced indexing with an integer-array +# 使用整数数组进行进阶索引 >>> index = np.array([2, 4, 0, 4, 4, 4]) >>> y[index] array([-2, -4, 0, -4, -4, -4]) @@ -107,7 +104,7 @@ array([-2, -4, 0, -4, -4, -4]) -The instruction for accessing the contents of `y` in this way is straight-forward to interpret. Each entry of the index-array is used to access an element from `y`, as illustrated here: +使用这种方法访问 `y` 成员的规则很容易理解。整数数组的每一个成员都被用来访问 `y` 的一个成员,如下: \begin{equation} @@ -126,26 +123,26 @@ The instruction for accessing the contents of `y` in this way is straight-forwar \end{equation} -This returns a *copy* of the data, as do all occurrences of advanced indexing. +和所有进阶索引的结果一样,这将返回数据的*复制品*。 ```python -# advanced indexing returns a copy +# 进阶索引返回复制品 >>> np.shares_memory(y, y[index]) False ``` -The indexing array can have an arbitrary shape; *the resulting array will match that shape*. +索引数组可以有着任意的形状;*返回的数组会有着相同的形状*。 ```python -# utilizing a 2D-array as an index +# 使用2维数组作为索引 >>> index_2d = np.array([[ 1, 2, 0], ... [ 5, 5, 5], ... [ 2, 3, 4]]) -# the resulting shape matches the shape of the indexing array +# 返回的数组形状于索引数组一样 >>> y[index_2d] array([[-1, -2, 0], [-5, -5, -5], @@ -175,15 +172,15 @@ array([[-1, -2, 0],
-**Reading Comprehension: Integer Array Indexing (1-D)** +**阅读理解:整数数组索引(1维)** -Given the following array: +设以下数组: ```python y = np.array([ 0, -1, -2, -3, -4, -5]) ``` -Use advanced indexing, using an integer-array, to produce the following arrays: +通过进阶索引,使用一个整数数组索引来产生以下数组: ```python # 1 @@ -206,14 +203,14 @@ array([[-2], -### Indexing into N-Dimensional Arrays +### 索引N维数组 -In the preceding examples, working with a 1-dimensional array, we specified a single index-array to access the contents along the only dimension of that array. As you may guess, in order to perform this variety of indexing on an $N$-dimensional array, we must specify $N$ index-arrays; one for each dimension. +在之前处理1维数组的例子中,我们提供了一个索引数组来通过数组唯一的维度访问其成员。你可能也猜到了,为了用相似的方法访问 $N$ 维数组,我们必须提供 $N$ 个索引数组;每个对应一个维度。 -Each of the $N$ index-arrays must have the same shape, and their common shape determines the shape of the resulting array. The corresponding entries of each of the $N$ index-arrays are used to specify a specific array element to be accessed. For example, consider the following 3-dimensional array whose elements we will be accessing: +所有 $N$ 个索引数组必须有着一样的形状,而且它们共享的形状决定了返回数组的形状。所有 $N$ 个索引数组的对应成员将用来作为索引来访问数组的一个具体的成员。比如说,设以下3维数组: ```python -# Indexing a 3D array using integer index-arrays +# 使用整数索引数组索引一个3维数组 >>> z = np.array([[[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]], @@ -223,22 +220,22 @@ Each of the $N$ index-arrays must have the same shape, and their common shape de ... [20, 21, 22, 23]]]) ``` -We specify three index-arrays; the indices to be accessed along axis-0, axis-1, and axis-2, respectively. Suppose we want to produce the array: `array([ 3, 23, 4])`. The layout of these elements is as follows: +我们输入三个索引数组,分别对应着在轴0,轴1,和轴2的该访问的索引。如果我们项返回数组:`array([ 3, 23, 4])`,这些成员的位置如下: -- `3`: sheet-0, row-0, column-3 -- `23`: sheet-1, row-2, column-3 -- `4`: sheet-0, row-1, column-0 +- `3`:页0,行0,列3 +- `23`:页1,行2,列3 +- `4`:页0,行1,列0 -Each index-array must have a shape (3,) in order to produce the result of the appropriate shape. The index-array supplied for axis-0 must be `np.array([0, 1, 0])` in order to select sheet-0 for `3`, sheet-1 for `23`, and then sheet-0 for `4`. The other index-arrays are formed similarly. +每个索引数组必须有着形状 (3,) 来返回正确形状的数组。为轴0输入的数组必须是 `np.array([0, 1, 0])` 来为 `3` 选择页0,为 `23` 选择页1,和为 `4` 选择页0。另外两个索引数组也是相似的。 ```python -# specifies subsequent sheets to access +# 描述每个成员的页 >>> ind0 = np.array([0, 1, 0]) -# specifies subsequent rows to access +# 描述每个成员的行 >>> ind1 = np.array([0, 2, 1]) -# specifies subsequent columns to access +# 描述每个成员的列 >>> ind2 = np.array([3, 3, 0]) >>> z[ind0, ind1, ind2] @@ -246,7 +243,7 @@ array([ 3, 23, 4]) ``` -Formally, the index-arrays are traversed simultaneously using [row-major ordering](https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/ArrayTraversal.html), and each combination of integer-indices is used to index into `z` and populate the corresponding element in the resulting array. +正式来讲,索引数组将通过[行优先顺序](https://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/ArrayTraversal.html)被遍历,而每一个整数索引的组合将被用来索引 `z` 并填入返回数组的对应位置。 \begin{equation} @@ -281,7 +278,7 @@ out[2] \\ ```python -# Using integer index-arrays to produce a shape(2, 2) result +# 使用整数索引数组来返回一个形状为 (2, 2) 的数组 >>> ind0 = np.array([1, 1, 0, 1]).reshape(2, 2) >>> ind1 = np.array([1, 2, 0, 0]).reshape(2, 2) >>> ind2 = np.array([1, 3, 1, 3]).reshape(2, 2) @@ -311,9 +308,9 @@ array([[17, 23],
-**Reading Comprehension: Integer Array Indexing (N-D)** +**阅读理解:整数数组索引(N维)** -Given the following array: +设以下数组: ```python >>> z = np.array([[[ 0, 1, 2, 3], @@ -325,7 +322,7 @@ Given the following array: ... [20, 21, 22, 23]]]) ``` -Use advanced indexing, using integer-arrays, to produce the following arrays: +通过进阶索引,使用整数数组索引来返回以下数组: ```python # 1 @@ -343,25 +340,25 @@ array([[ 0, 23],
-**Takeaway:** +**经验**: -An $N$-dimensional array's contents can be accessed by supplying $N$ index-arrays of integers; one for each axis of data. The index-arrays must have the same shape as one another, and this common shape determines the shape of the resulting array. This is a form of advanced indexing, and thus a copy of the parent array's data is created. +$N$ 维数组的成员可以通过输入 $N$ 个整数的索引数组来访问,每个索引对应着数据的一个轴。索引数组之间形状必须相同,而它们共享的形状决定了返回数组的形状。这是进阶索引的一种,因此这将创建一份父数组的复制品。
-## Boolean-Array Indexing -NumPy also permits the use of a boolean-valued array as an index, to perform advanced indexing on an array. In its simplest form, this is an extremely intuitive and elegant method for selecting contents from an array based on logical conditions. +## 布尔数组索引 +NumPy也支持使用布尔值数组来作为索引的进阶索引数组的方法。在最简单的情况下,这是一个非常易懂优雅的根据逻辑条件选中数组成员的方法。 ```python -# advanced indexing using a boolean-array +# 使用布尔数组进行进阶索引 >>> x = np.array([[[-0.26, 0.49, 0.18], ... [ 0.43, 0.3 , 0.29]], ... ... [[-0.44, 0.3 , 0.28], ... [ 0.27, -0.09, -0.13]]]) -# `True` wherever `x` is positive +# 当 `x` 为正数时是 `True` >>> bool_ind = x > 0 >>> bool_ind array([[[False, True, True], @@ -376,15 +373,15 @@ array([ 0.49, 0.18, 0.43, 0.3 , 0.29, 0.3 , 0.28, 0.27]) >>> np.shares_memory(x, x[bool_ind]) False ``` -In its simplest form, boolean indexing behaves as follows: Suppose `x` is an $N$-dimensional array, and `ind` is a boolean-value array *of the same shape as* `x`. Then `x[ind]` returns a 1-dimensional array, which is formed by traversing `x` and `ind` using [row-major ordering](https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/ArrayTraversal.html). Wherever an element of `ind` is `True`, the corresponding entry of `x` is added to the end of the resulting array. Refer to the preceding example and convince yourself that this is the behavior that is exhibited. +在最简单的情况下,布尔索引的行为如下:设 `x` 为 $N$ 维数组,`ind` 为一个和 `x` *一样形状*的布尔数组。那么 `x[ind]` 将返回一个1维数组,根据使用[行优先顺序](https://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/ArrayTraversal.html)遍历 `x` 和 `ind` 产生。每当 `ind` 的一个成员为 `True` 时,就往返回数组添加 `x` 的对应成员。请检查以上范例来确认这个行为是否如这里所描述一样。
-**Reading Comprehension: Boolean Indexing** +**阅读理解:布尔索引** -Given the following array: +设以下数组: ```python >>> h = np.array([[ 0.01, 0.03, 0.1 , 0.25], @@ -392,21 +389,21 @@ Given the following array: ... [-0.29, 0.13, -0.26, 0.33]]) ``` -Use boolean array-indexing and NumPy's [logical functions](https://docs.scipy.org/doc/numpy/reference/routines.logic.html) to select the contents of `h` that satisfy the following conditions. Because you are dealing with floating-point numbers, [you should not require that two values are exactly equal](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Understanding-Numerical-Precision); rather, make use of the function [numpy.isclose](https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html). +使用布尔数组索引和NumPy的[逻辑函数](https://docs.scipy.org/doc/numpy/reference/routines.logic.html)来选中 `h` 满足一下条件的成员。因为你在处理浮点数,[你不应该检查两值完全相等](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Understanding-Numerical-Precision);反而,使用函数[numpy.isclose](https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html)。 -1. All negative entries in `h` -2. All entries in `h` "equal" to `0.01` or `0.33` -3. All entries of `h` that fall within the domain `(0.1, 0.3) +1. 所有 `h` 的负成员 +2. 所有 `h` “等于” `0.01` 或 `0.33` 的成员 +3. 所有 `h` 在域 `(0.1, 0.3)` 之间的成员。
-#### Converting a Boolean Index-Array to Integer index-arrays: numpy.where -The function [numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) can be used to take a boolean-valued array, and produce the *tuple* of index-arrays that access the `True` entries of that array, via integer array indexing (discussed at the beginning of this section). +### 将布尔索引数组转化为整数索引数组:numpy.where +函数[numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html)可以用来接受一个布尔值数组并返回一*元组*的通过整数数组索引(在本节开头讨论过)访问数组中为 `True` 的成员的索引数组。 ```python -# demonstrating `np.where` +# 演示 `np.where` >>> bool_ind array([[[False, True, True], [ True, True, True]], @@ -420,43 +417,41 @@ array([[[False, True, True], array([1, 2, 0, 1, 2, 1, 2, 0], dtype=int64)) ``` -In this example, a tuple of three integer-valued index-arrays are returned, one for each dimension of `bool_ind`. See that index-arrays indicate the `True` entries of `bool_ind`. Furthermore, recall that `bool_ind` was created to access the positive entries of `x`; the tuple of index-arrays can thus be used to the exact same end. +本例返回了三个整数索引数组的元组,每个数组对应 `bool_ind` 的一个维度。这些索引数组描述了 `bool_ind` 中为 `True` 的位置。同时,请回忆,`bool_ind` 是为了访问 `x` 中正数而创建的数组;这个函数返回的索引数组元组也可以用来达成相同的目的。 ```python >>> ind0, ind1, ind2 = np.where(bool_ind) >>> x[ind0, ind1, ind2] array([ 0.49, 0.18, 0.43, 0.3 , 0.29, 0.3 , 0.28, 0.27]) -# unpacking the arrays is not necessary, you can -# use the tuple as an index +# 没有必要解包这些数组。你可以之间将元组作为索引使用 >>> x[np.where(bool_ind)] array([ 0.49, 0.18, 0.43, 0.3 , 0.29, 0.3 , 0.28, 0.27]) ``` -`np.where` is particularly useful when we want insight into *where* specific conditions are met within an array. Suppose, for instance, we want to know which sheets in `x` contain values greater than 0.4: +`np.where` 在我们想要了解数组的*哪里*(where)满足了某个特殊条件时很有用。比如说,假设我们想要知道 `x` 中的哪些页包含了大于0.4的值: ```python -# which sheets in `x` contain a value -# greater than 0.4? +# `x` 的哪些页包含大于0.4的值? >>> ind0, ind1, ind2 = np.where(x > 0.4) -# get rid of redundant answers +# 删除重复的答案 >>> np.unique(ind0) array([0], dtype=int64) -# only sheet-0 contains such values +# 只有页0有这样的值 ``` -Armed with NumPy's suite of [logical functions](https://docs.scipy.org/doc/numpy/reference/routines.logic.html), boolean-array indexing provides a sleek interface for accessing the particular contents of an array, irrespective of the array's shape and the layout of its contents. This method of indexing is especially powerful in the context of performing augmented updates to an array, which is the subject of the following subsection. +有着对NumPy[逻辑函数](https://docs.scipy.org/doc/numpy/reference/routines.logic.html)的理解,布尔数组索引为访问数组成员提供了一个方便,不在乎数组形状和内容格式的操作界面。这种索引方法在对数组进行进行增强更新时极其有用。我们将在下一小节讨论它。
-**Reading Comprehension: numpy.where** +**阅读理解:numpy.where** -Given the array +设数组: ```python >>> b = np.array([[False, False, True], @@ -464,22 +459,22 @@ Given the array ... [ True, True, False]], dtype=bool) ``` -*Predict* what the output of `np.where(b)` is. +*预测* `np.where(b)` 的输出是什么。
-## In-Place & Augmented Assignments via Advanced Indexing +## 通过进阶索引进行原地和增强赋值 -Although advanced indexing does not produce a [*view* of the underlying data](https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/BasicIndexing.html#Producing-a-View-of-an-Array), it can still be used to facilitate in-place and augmented assignments to regions of an array. Suppose, for instance, that you want to threshold the contents of an array such that all of its negative-valued entries are replaced with 0. Boolean indexing makes this task trivial to perform via in-place assignment: +虽然进阶索引不提供[内置数据的*视阈*](https://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/BasicIndexing.html#Producing-a-View-of-an-Array),它依然可以用来帮助我们对数组其中的区域进行原地和增强赋值。比如说,假设你想要对数组进行阀值操作,使得其所有负成员都被0代替。通过原地复制,布尔索引将会使得这个工作极其轻松: ```python -# assignment via advanced indexing +# 通过进阶索引赋值 >>> x = np.array([[ 0.38, -0.16, 0.38, -0.41, -0.04], ... [-0.47, -0.01, -0.18, -0.5 , -0.49], ... [ 0.02, 0.4 , 0.33, 0.33, -0.13]]) -# set all negative entries of `x` to 0 (broadcasting is used) +# 将所有 `x` 的负成员设为0(这里自动使用了广播) >>> x[x < 0] = 0 >>> x array([[ 0.38, 0. , 0.38, 0. , 0. ], @@ -487,16 +482,16 @@ array([[ 0.38, 0. , 0.38, 0. , 0. ], [ 0.02, 0.4 , 0.33, 0.33, 0. ]]) ``` -We also demonstrate the use of integer-valued index-arrays to perform an augmented assignment. +我们也将演示使用整数索引数组来进行增强赋值的方法。 ```python -# augmented assignment via integer-arrays +# 通过整数数组进行增强赋值 >>> ind0 = np.array([0, -1]) >>> ind1 = np.array([0, 1]) >>> x[ind0, ind1] array([ 0.38, 0.4]) -# equivalent: x[ 0, 0] *= 100 -# x[-1, 1] *= 100 +# 等值于:x[ 0, 0] *= 100 +# x[-1, 1] *= 100 >>> x[ind0, ind1] *= 100 >>> x @@ -507,16 +502,16 @@ array([[ 38., 0. , 0.38 , 0., 0. ], -Recall that redundant entries in an array can be specified via integer array indexing. An augmented assignment *will only be performed once on redundant entries*. +请回忆,你可以通过整数数组索引来访问数组中重复的成员。增强赋值*只会为重复成员进行一次*。 ```python >>> y = np.array([4, 6, 8]) -# y[0] is accessed three times and y[2] one time +# y[0]被访问了三次,而y[2]被访问了一次 >>> y[np.array([0, 0, 0, 2])] array([4, 4, 4, 8]) -# the augmented update is only applied once to y[0] +# 增强更新仅仅对y[0]进行一次 >>> y[np.array([0, 0, 0, 2])] += 1 >>> y array([5, 6, 9]) @@ -526,9 +521,9 @@ array([5, 6, 9])
-**Reading Comprehension: Assignment via advanced indexing** +**阅读理解:使用进阶索引赋值** -Given the array +设数组: ```python >>> x = np.array([[ 0.58, 0.05, 0.84, 0.21], @@ -537,16 +532,16 @@ Given the array ... [ 0.84, 0.76, 0.25, 0.07]]) ``` -Replace the diagonal elements of `x` with `(-1, -2, -3, -4)`, and add `1` to all values in `x` that are greater than `0.8`. +将 `x` 的对角线成员代替为 `(-1, -2, -3, -4)`,并对 `x` 中所有大于 `0.8` 的成员加 `1`。
-## Combining Basic and Advanced Indexing Schemes -Integer- and boolean-valued arrays can be used in conjunction with `slice`, `numpy.newaxis`, and `int` objects to form indices that combine basic and advanced indexing schemes. +## 混合使用基础和进阶索引 +整数和布尔值数组可以和 `slice`,`numpy.newaxis`,以及 `int` 对象混合使用来创建同时使用基础和进阶索引模式的索引。 ```python -# combining advanced and basic indexing techniques +# 混合使用进阶和基础索引技巧 >>> z = np.array([[[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]], @@ -557,27 +552,27 @@ Integer- and boolean-valued arrays can be used in conjunction with `slice`, `num >>> ind0 = np.array([True, False]) -# select sheet-0, all rows, last column +# 选中页0,所有行,和最后一列 >>> z[ind0, :, -1] array([[ 3, 7, 11]]) ``` -The rules for resolving the various possible combinations of basic and advanced indexing are nontrivial. Refer to the [official NumPy documentation](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing) for a detailed description for these rules. In practice, basic and advanced indexing can typically be used independently from one another. +处理混合基础和进阶索引的规则不能被简短地在此讨论。请查看[官方NumPy说明文档](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing)来仔细阅读这些规则。实际操作中,基础和进阶索引一般都会单独使用。 -## Links to Official Documentation +## 官方说明文档链接 -- [Advanced Indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing) -- [Logical Functions](https://docs.scipy.org/doc/numpy/reference/routines.logic.html) +- [进阶索引](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing) +- [逻辑函数](https://docs.scipy.org/doc/numpy/reference/routines.logic.html) - [numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) -- [Combining Basics and Advanced Indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing) +- [混合基础和进阶索引](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing) -## Reading Comprehension Solutions +## 阅读理解答案: -**Integer Array Indexing (1-D): Solution** +**整数数组索引(1维):解** ```python y = np.array([ 0, -1, -2, -3, -4, -5]) @@ -613,7 +608,7 @@ array([[-2], -**Integer Array Indexing (N-D): Solution** +**整数数组索引(N维):解** ```python >>> z = np.array([[[ 0, 1, 2, 3], @@ -645,7 +640,7 @@ array([[ 0, 23], -**Boolean Indexing: Solution** +**布尔索引:解** ```python >>> h = np.array([[ 0.01, 0.03, 0.1 , 0.25], @@ -666,9 +661,9 @@ array([ 0.25, 0.22, 0.15, 0.13]) -**numpy.where: Solution** +**numpy.where:解** -Given the array +设数组: ```python >>> b = np.array([[False, False, True], @@ -676,9 +671,9 @@ Given the array ... [ True, True, False]], dtype=bool) ``` -*Predict* what the output of `np.where(b)` is. +*预测* `np.where(b)` 的输出是什么。 -This will return a tuple of two integer-valued index-arrays. These contain the indices, along axis-0 and axis-1 respectively, where `b` contains the value `True`. The indices are ordered by traversing `b` in row-major order. It returns: +这将会返回一个有着两个整数索引数组的元组。它们分别包含着 `b` 的成员值为 `True` 的位置对应轴0和轴1的索引。这些索引的顺序是根据行优先顺序遍历 `b` 产生的。这将返回: ```python (array([0, 1, 2, 2], array([2, 1, 0, 1]) @@ -686,7 +681,7 @@ This will return a tuple of two integer-valued index-arrays. These contain the i -**Assignment via advanced indexing** +**使用进阶索引赋值:解** ```python >>> x = np.array([[ 0.58, 0.05, 0.84, 0.21], diff --git a/Python/Module3_IntroducingNumpy/ArrayTraversal.md b/Python/Module3_IntroducingNumpy/ArrayTraversal.md index 115b2f3..ac6197d 100644 --- a/Python/Module3_IntroducingNumpy/ArrayTraversal.md +++ b/Python/Module3_IntroducingNumpy/ArrayTraversal.md @@ -4,42 +4,42 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Numpy array traversal ordering, Difficulty: Medium, Category: Section :keywords: row-major order, c order, column-major order, f order, traversal, array iteration -``` + -# Iterating Over Arrays & Array-Traversal Order -In this section, you will learn: +# 迭代数组和数组遍历顺序 +在本节中,你将会学到: -- About NumPy's functions for iterating over an array -- That there is more than one valid way for NumPy to perform this operation, which amounts to how NumPy traverses a multidimensional array. -- The row-major array traversal methodology, which is utilized by NumPy by default. +- NumPy迭代数组的函数。 +- 有不止一个合理的方法用NumPy在迭代数组,区别仅仅在于NumPy遍历多维数组的方法。 +- NumPy默认使用的行优先的遍历方法。 -NumPy provides valuable tools for iterating over any array, such that each element can be visited in the array, regardless of the array's shape. For example, recall that Python's built-in `enumerate` function permits us to produce each item in an iterable, along with its index of iteration: +NumPy提供了无论数组形状都可以完整迭代数组每一个成员的重要工具。比如说,请回忆,Python内置的 `enumerate` 函数允许我们一个一个获取可迭代物中的每一个成员,以及它在迭代中的索引: ```python -# enumerating the items in an iterable +# 枚举可迭代物中的成员 >>> [i for i in enumerate("abcdef")] [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')] ``` -Similarly, NumPy provides the [ndenumerate](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html#numpy.ndenumerate) function, which enumerates each element in an N-dimensional array, specifying the N-dimensional index for each element. +相似的,NumPy提供了[ndenumerate](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html#numpy.ndenumerate)函数。它枚举N维数组中的每一个成员并同时提供它在数组中的N维索引。 ```python >>> import numpy as np -# Demonstrating `np.ndenumerate`. -# A shape-(2, 2, 3) array +# 演示 `np.ndenumerate` +# 形状为 (2, 2, 3) 的数组 >>> x = np.array([[[ 25, 6, -35], ... [ 9, -40, -29]], ... @@ -61,7 +61,7 @@ Similarly, NumPy provides the [ndenumerate](https://docs.scipy.org/doc/numpy/ref ((1, 1, 2), -45)] ``` -See that each triplet of integers specifies the index for the corresponding array element: +请注意,有三个成员的整数数组描述了对应数组成员的索引: ```python >>> x[0, 0, 0] @@ -77,45 +77,45 @@ See that each triplet of integers specifies the index for the corresponding arra 9 ``` -See [the official NumPy documentation](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#iterating-over-arrays) for a complete listing of functions that facilitate iterating over arrays. The official documentation also provides [a detailed treatment of array iteration](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#iterating-over-arrays), which is far more detailed than is warranted here. Next, we must discuss the default ordering that NumPy uses when traversing a N-dimensional array. +请查看[官方NumPy说明文档](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#iterating-over-arrays)来阅读完整的辅助迭代数组的函数列表。官方说明文档同时提供了[一个细致的迭代数组的教程](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#iterating-over-arrays),相比本文完整细致多很多。接下来,我们需要讨论NumPy在遍历N维数组时使用的默认顺序。 -## How to Traverse an Array: Row-major (C) vs Column-major (F) Traversal Ordering -Note the order in which `np.ndenumerate` iterated over `x`. It first traversed the columns within row-0 of sheet-0 of `x`, and then it traversed the columns within the row-1 of sheet-0, and so on. What is special about this traversal order? Why, for instance, didn't it traverse the rows within a given column instead? We can also see that there is not a unique ordering for a `reshape` function to adhere to. For example, the following reshape operation could sensibly return either of the following results: +## 如何遍历数组:行优先(C)vs 列优先(F)遍历顺序 +请注意 `np.ndenumerate` 迭代 `x` 的顺序。它首先遍历了 `x` 的页0行0的列,然后它遍历了页0行1的列,如此反复。这个遍历顺序有什么特殊的呢?比如说,为什么它不首先遍历每一列中的行呢?我们也可以发现 `reshape` 函数没有必要遵循什么独特的顺序。不如说,以下的重塑操作完全可以合理地返回两个结果中的任何一个 ``` array([0, 1, 2, 3, 4, 5]).reshape(2, 3) --> array([[0, 1, 2], or array([[0, 2, 4], [3, 4, 5]]) [1, 3, 5]]) ``` -Both arrays are of the appropriate shape and preserve the ordering of the original sequence of numbers, depending on how you traverse them. The left array preserves the ordering of the original data if you traverse the columns within a row, and then proceed to the next row. This is known as **row-major** ordering. The array on the right preserves the ordering if you traverse the rows within a given column, and then transition to the next column. This is thus referred to as **column-major** ordering. One ordering is not inherently better than the other. That being said, *NumPy always defaults to row-major ordering whenever one of its functions involves array traversal*. +这两个返回的数组都有着合理的形状且,根据你遍历它们,都保存了原本数字序列的顺序。左边的数组当你首先遍历每一行中的列,然后再遍历下一行的时候保存了顺序。因此,这个叫做**行优先**顺序。右边的数组当你首先遍历每一列中的行,然后再遍历下一列的时候保存了顺序。因此,这个叫做**列优先**排序。没有说一个排序就一定比另外一个好。虽然如此,*NumPy的函数需要遍历数组时永远都会默认使用行优先顺序*。
-**Remember This:** +**记住这点**: -NumPy utilizes row-major ordering, as a default, for any operation that requires an array to be traversed. +NumPy在任何数组遍历操作时默认使用行优先顺序。
-These two orderings are simple enough to follow for a 2D-array, but how do they manifest in arrays with higher dimensions, where we have to worry not only about rows and columns, but potentially "stacks of sheets with rows and columns" (which would be a 4D array) and so on? The generic rules are as follows: +在处理2维数组时这两个顺序不是很烧脑,但是在处理更高维数组时它们该如何表现呢?我们不仅仅需要担心行和列,而可能会需要处理“几打成员为行列的页”(这会是一个4维数组)这种拗口的情况。基本规则如下: -- **Row-major ordering (C ordering) {NumPy's default}**: traverse an array by advancing the index of the *last axis*, first, until the end of that axis is reached, and then advance the index of the second-to last axis, and so on. -- **Column-major ordering (F ordering)**: traverse an array by advancing the index of the *first axis*, first, until the end of that axis is reached, and then advance the index of the second axis, and so on. +- **行优先顺序(C顺序){NumPy默认}**:遍历时首先增加*最后轴*的索引,直到遇到该轴的结尾,然后再增加倒数第二个索引,如此反复。 +- **列优先顺序(F顺序)**:遍历时首先增加*第一个轴*的索引,直到该轴的结尾,然后再增加第二个轴的索引,如此反复。
-**Note**: +**注**: -"Row-major" ordering is also referred to as "C-ordering" because this is the traversal method utilized in the C language. "Column-major" ordering, on the other hand, is also referred to as "F-ordering", because it is used by the Fortran language. NumPy functions, like `reshape` allow you to specify either `order="C"` (which is the default) or `order="F"` to control the order in which an array is traversed; these options thus correspond to row-major and column-major ordering. +“行优先”排序也称为“C顺序”的原因是因为这也是C语言使用的遍历方法。反之,“列优先”排序也称为“F排序”的原因是这也是Fortran语言使用的遍历方法。像 `reshape` 的NumPy函数允许你选择 `order="C"`(默认)或 `order="F"` 来控制数组遍历的顺序;这些选择对应行优先和列优先顺序。
-To make this more concrete, let's consider how NumPy reshapes a shape-(24,) array into a shape-(2,3,4) array: +为了使以上讨论更加实际,让我们考虑NumPy是如何将形状为 (24,) 的数组重塑为形状为 (2,3,4) 的数组: ```python -# reshape a shape-(24,) array into a shape-(2,3,4) array +# 将形状为 (24,) 的数组重塑为形状为 (2,3,4) 的数组 >>> np.arange(2*3*4).reshape(2,3,4) array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], @@ -126,84 +126,84 @@ array([[[ 0, 1, 2, 3], [20, 21, 22, 23]]]) ``` -Following NumPy's default row-major ordering, we can perform this reshaping by following these steps: +根据NumPy的默认行优先顺序,我们可以根据以下步骤进行重塑: - 1. Create an empty array of the desired shape: (2, 3, 4). - 2. Start by inserting the 0th element from the input array into the (0, 0, 0) element of the output array. - 3. Advance the index by *increasing the index of the last axis, first*, and inserting the following element from the input array. - 4. If you reach the end of an axis (axis-2, for instance, only has 4 slots), reset the index for that axis to 0, and advance the index of the preceding axis. Go back to 3. + 1. 创建一个形状为期望形状的空数组:(2, 3, 4)。 + 2. 首先将输入数组的第0个成员插入到输出数组的 (0, 0, 0) 位置。 + 3. *通过首先增加最后轴的索引*来进入到下一个位置,并将输入数组的下一个成员插入。 + 4. 如果你遇到了某轴的结尾(比如说,轴2只有4个位置),重置该轴的索引为0,并增加前面一个轴的索引。回到第3步。 -This traversal process is easier to understand when laid out explicitly: +这个遍历过程在一步步看到之后会更好理解: *** -**Reshaping a shape-(24,) array to a shape-(2,3,4) array, using NumPy's default "row-major" ordering** +**使用NumPy默认的“行优先”顺序,将形状为 (24,) 的数组重塑为形状为 (2,3,4) 的数组** ``` - Input Array Output Array + 输入数组 输出数组 ----------- --------------- - entry: 0 -> entry: (0, 0, 0) - entry: 1 -> entry: (0, 0, 1) - entry: 2 -> entry: (0, 0, 2) - entry: 3 -> entry: (0, 0, 3) *row-0 of sheet 0, filled. go to next row* - entry: 4 -> entry: (0, 1, 0) - entry: 5 -> entry: (0, 1, 1) - entry: 6 -> entry: (0, 1, 2) - entry: 7 -> entry: (0, 1, 3) *row-1 of sheet 0, filled. go to next row* - entry: 8 -> entry: (0, 2, 0) - entry: 9 -> entry: (0, 2, 1) - entry:10 -> entry: (0, 2, 2) - entry:11 -> entry: (0, 2, 3) *row-2 of sheet 0, filled. go to next sheet!* - - entry:12 -> entry: (1, 0, 0) - entry:13 -> entry: (1, 0, 1) - entry:14 -> entry: (1, 0, 2) - entry:15 -> entry: (1, 0, 3) *row-0 of sheet 1, filled. go to next row* - entry:16 -> entry: (1, 1, 0) - entry:17 -> entry: (1, 1, 1) - entry:18 -> entry: (1, 1, 2) - entry:19 -> entry: (1, 1, 3) *row-1 of sheet 1, filled. go to next row* - entry:20 -> entry: (1, 2, 0) - entry:21 -> entry: (1, 2, 1) - entry:22 -> entry: (1, 2, 2) - entry:23 -> entry: (1, 2, 3) *row-2 of sheet 1, filled. Done!* + 成员: 0 -> 成员: (0, 0, 0) + 成员: 1 -> 成员: (0, 0, 1) + 成员: 2 -> 成员: (0, 0, 2) + 成员: 3 -> 成员: (0, 0, 3) *页0行0填满。进入到下一行* + 成员: 4 -> 成员: (0, 1, 0) + 成员: 5 -> 成员: (0, 1, 1) + 成员: 6 -> 成员: (0, 1, 2) + 成员: 7 -> 成员: (0, 1, 3) *页1行0填满。进入到下一行* + 成员: 8 -> 成员: (0, 2, 0) + 成员: 9 -> 成员: (0, 2, 1) + 成员:10 -> 成员: (0, 2, 2) + 成员:11 -> 成员: (0, 2, 3) *页0行2填满。进入到下一页!* + + 成员:12 -> 成员: (1, 0, 0) + 成员:13 -> 成员: (1, 0, 1) + 成员:14 -> 成员: (1, 0, 2) + 成员:15 -> 成员: (1, 0, 3) *页1行0填满。进入到下一行* + 成员:16 -> 成员: (1, 1, 0) + 成员:17 -> 成员: (1, 1, 1) + 成员:18 -> 成员: (1, 1, 2) + 成员:19 -> 成员: (1, 1, 3) *页1行1填满。进入到下一行* + 成员:20 -> 成员: (1, 2, 0) + 成员:21 -> 成员: (1, 2, 1) + 成员:22 -> 成员: (1, 2, 2) + 成员:23 -> 成员: (1, 2, 3) *页1行2填满。完成!* ``` *** -The same process can be extended to reshape one multidimensional array into another multidimensional array of a different shape. The input and output arrays are simply traversed, respectively, according to "row-major" rules. Suppose we want to reshape a shape-(2,3,4) array into a shape-(6,4) array. This process would be carried out as follows: +同样的过程可以扩展到将单个多维数组重塑成另外一个形状不同的多维数组的情况下。我们只需要使用“行优先”规则来分别遍历输入和输出数组就行了。假设我们想要将一个形状为 (2,3,4) 的数组重塑为形状为 (6,4) 的数组,过程如下: *** -**Reshaping a shape-(2,3,4) into a shape(6,4) array using NumPy's default "row-major" ordering** +**使用NumPy默认的“行优先”顺序,将形状为 (2,3,4) 的数组重塑为形状为 (6,4) 的数组** ``` - Input Array Output Array + 输入数组 输出数组 ---------------- --------------- - entry: (0, 0, 0) -> entry: (0, 0) - entry: (0, 0, 1) -> entry: (0, 1) - entry: (0, 0, 2) -> entry: (0, 2) - entry: (0, 0, 3) -> entry: (0, 3) - entry: (0, 1, 0) -> entry: (1, 0) - ... - ... - entry: (1, 2, 3) -> entry: (5, 3) + 成员: (0, 0, 0) -> 成员: (0, 0) + 成员: (0, 0, 1) -> 成员: (0, 1) + 成员: (0, 0, 2) -> 成员: (0, 2) + 成员: (0, 0, 3) -> 成员: (0, 3) + 成员: (0, 1, 0) -> 成员: (1, 0) + ... + ... + 成员: (1, 2, 3) -> 成员: (5, 3) ``` -Although this bookkeeping may seem a bit tedious at first glance, you will likely find that you are able to build up enough intuition for row-major ordering, to the point where you never need to write out these tables in full! The ability to reshape an array to adjust the way you can access an array's data is commonly used in data science applications. Furthermore, understanding how NumPy handles array traversal is critical to understanding more advanced concepts like array-broadcasting and advanced indexing. +虽然这样的记录可能第一眼看起来很麻烦,但是你很可能将会发现自己对行优先排序有了足够的直观理解来永远不需要像上面这样写整个表格!重塑数组形状来修改你访问数组数据的能力在数据科学应用中非常常用。同时,理解NumPy如何处理数组遍历是理解类似于数组广播(array broadcasting)和进阶索引(advanced indexing)必不可缺的奠基石。
-**Reshape is its own inverse**: +**reshape是它自己的逆操作**: -According to this discussion, `reshape` can effectively "undo" itself: `np.arange(10).reshape(5,2).reshape(10)` will return `array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])`. Take some time to consider why this will always be true, no matter how many intermediary reshapes are performed. +根据以上的讨论,`reshape` 完全可以“逆反”它自己的作用:`np.arange(10).reshape(5,2).reshape(10)` 将会返回 `array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])`。花些时间来理解为什么这一点永远成立,不论中间有着多少步重塑。
-## Links to Official Documentation +## 官方说明文档链接 -- [Definition of row major ordering](https://docs.scipy.org/doc/numpy/glossary.html#term-row-major) -- [Definition of column major ordering](https://docs.scipy.org/doc/numpy/glossary.html#term-column-major) -- [Routines for iterating over arrays](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#iterating-over-arrays) -- [Detailed description of array iteration](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#iterating-over-arrays) +- [行优先顺序的定义](https://docs.scipy.org/doc/numpy/glossary.html#term-row-major) +- [列优先顺序的定义](https://docs.scipy.org/doc/numpy/glossary.html#term-column-major) +- [迭代数组常规](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html#iterating-over-arrays) +- [数组迭代的细致描述](https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#iterating-over-arrays) diff --git a/Python/Module3_IntroducingNumpy/BasicArrayAttributes.md b/Python/Module3_IntroducingNumpy/BasicArrayAttributes.md index 527ee44..87005b6 100644 --- a/Python/Module3_IntroducingNumpy/BasicArrayAttributes.md +++ b/Python/Module3_IntroducingNumpy/BasicArrayAttributes.md @@ -4,25 +4,25 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Numpy array attributes, Difficulty: Easy, Category: Section :keywords: ndim, shape, size, itemsize, dtype, examples -``` + -# Basic Array Attributes -Armed with our understanding of multidimensional NumPy arrays, we now look at methods for programmatically inspecting an array's attributes (e.g. its dimensionality). It is especially important to understand what an array's "shape" is. +# 基本的数组属性 +有了我们对NumPy多维数组的理解后,我们现在来了解一些使用代码来查看数组属性(例如维度)的方法吧。理解数组的“形状”(shape)是什么极其重要。 -We will use the following array to provide context for our discussion: +我们将使用以下的数组来进行讨论: ```python >>> import numpy as np @@ -35,18 +35,18 @@ We will use the following array to provide context for our discussion: ... [[16, 17, 18, 19], ... [20, 21, 22, 23]]]) ``` -According to the preceding discussion, it is a 3-dimensional array structured such that: +根据之前的讨论,这是一个有着一下结构的3维数组: - - axis-0 discerns which of the **3 sheets** to select from. - - axis-1 discerns which of the **2 rows**, in any sheet, to select from. - - axis-2 discerns which of the **4 columns**, in any sheet and row, to select from. + - 轴0描述从**3页**中选中哪一个。 + - 轴1描述从任何一页中的**2行**中选中哪一个。 + - 轴2描述从任何一页和行中的**4列**中选中哪一个。 **ndarray.ndim**: -The number of axes (dimensions) of the array. +数组的轴(维度)数。 ```python -# dimensionality of the array +# 数组的维度 >>> example_array.ndim 3 ``` @@ -55,43 +55,43 @@ The number of axes (dimensions) of the array. **ndarray.shape**: -A tuple of integers indicating the number of elements that are stored along each dimension of the array. For a 2D-array with $N$ rows and $M$ columns, shape will be $(N, M)$. The length of this shape-tuple is therefore equal to the number of dimensions of the array. +成员为代表数组每个维度的项目数量的整数元组。如果一个2维数组有着 $N$ 行和 $M$ 列,那么形状将是 $(N, M)$。所以这个形状元组的长度等于数组的维度。 ```python -# shape of the array +# 数组的形状 >>> example_array.shape (3, 2, 4) ``` **ndarray.size**: -The total number of elements of the array. This is equal to the product of the elements of the array's shape. +这个数组总共的成员数。这等于数组形状的每个数的乘积。 ```python -# size of the array: the number of elements it stores +# 数组的大小:数组中存了多少个成员 >>> example_array.size 24 ``` **ndarray.dtype**: -An object describing the data type of the elements in the array. Recall that NumPy's ND-arrays are *homogeneous*: they can only posses numbers of a uniform data type. +描述数组成员的数据类型的对象。请回忆,NumPy的N维数组都是*同质*(homogenous)的:它们只能拥有同样数据类型的数字。 ```python -# `example_array` contains integers, each of which are stored using 32 bits of memory +# `example_array` 存储整数。每个整数使用32比特(bit)的内存 >>> example_array.dtype dtype('int32') ``` **ndarray.itemsize**: -The size, in bytes (8 bits is 1 byte), of each element of the array. For example, an array of elements of type `float64` has itemsize 8 $(= \frac{64}{8})$, while an array of type `complex32` has itemsize 4 $(= \frac{32}{8})$. +数组每个成员的大小,单位是字节(byte)(1字节等于8比特)。比如说,类型为 `float64` 的数组的itemsize就是8 $(= \frac{64}{8})$,而类型为 `complex32` 的数组的itemsize就是4 $(= \frac{32}{8})$。 ```python -# each integer in `example_array` is represented using 4 bytes (32 bits) of memory +# `example_array` 的每个整数占用4字节(32比特)的内存 >>> example_array.itemsize 4 ``` -## Links to Official Documentation +## 官方说明文档链接 -- [Array attributes](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-attributes) +- [数组属性](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-attributes) diff --git a/Python/Module3_IntroducingNumpy/BasicIndexing.md b/Python/Module3_IntroducingNumpy/BasicIndexing.md index 54c20e1..1b859d3 100644 --- a/Python/Module3_IntroducingNumpy/BasicIndexing.md +++ b/Python/Module3_IntroducingNumpy/BasicIndexing.md @@ -4,139 +4,133 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Numpy array basic indexing, Difficulty: Medium, Category: Section :keywords: basic index, slice, no copy index, multidimensional array, nd array, view, reverse, axis -``` + -# Introducing Basic and Advanced Indexing +# 基础和进阶索引简介 -Thus far we have seen that we can access the contents of a NumPy array by specifying an integer or slice-object as an index for each one of its dimensions. Indexing into and slicing along the dimensions of an array are known as basic indexing. NumPy also provides a sophisticated system of "advanced indexing", which permits us powerful means for accessing elements of an array that is flexible beyond specifying integers and slices along axes. For example, we can use advanced indexing to access all of the negative-valued elements from `x`. +到现在为止,我们看到我们可以通过为数组每一维度提供整数或切片对象来访问NumPy数组的成员。索引和切片数组的维度叫做基础索引(basic indexing)。NumPy也提供了一套成熟的“进阶索引”(advanced indexing)系统来为我们提供强大的不仅限于为轴提供整数和切片的访问数组成员的方法。比如说,我们可以使用进阶索引来访问所有 `x` 的负数成员。 ```python -# demonstrating basic indexing and advanced indexing +# 演示基本和进阶索引 >>> import numpy as np >>> x = np.array([[ -5, 2, 0, -7], ... [ -1, 9, 3, 8], ... [ -3, -3, 4, 6]]) -# Access the column-1 of row-0 and row-2. -# This is an example of basic indexing. -# A "view" of the underlying data in `x` -# is produced; no data is copied. +# 访问行0和行2的列1. +# 这是一个基础索引的范例。这将会创建一个 `x` 内在数据的 +# “视阈”(view);没有任何数据会被复制。 >>> x[::2, 1] array([ 2, -3]) -# An example of advanced indexing. -# Access all negative elements in `x`. -# This produces a copy of the accessed data. +# 进阶索引的范例。 +# 访问所有 `x` 的负数成员。这将复制被访问数据。 >>> x[x < 0] array([-5, -7, -1, -3, -3]) ``` -We will see that, where basic indexing provides us with a *view* of the data within the array, without making a copy of it, advanced indexing requires that a copy of the accessed data be made. Here, we will define basic indexing and understand the nuances of working with views of arrays. The next section, then, is dedicated to understanding advanced indexing. +我们将会看到虽然基础索引为我们提供了数组数据的*视阈*(view)而不复制其成员,进阶索引会需要复制数组被访问的数据。在这里,我们将定义基础索引并理解操作数组视阈的一些细节。在下一节,我们会具体学习进阶索引。 -## Basic Indexing -We begin this subsection by defining precisely what basic indexing is. Next, we will touch on each component of this definition, and lastly we will delve into the significance of basic indexing in the way it permits us to reference the underlying data of an array without copying it. +## 基础索引 +我们在本小节之初将定义基础索引。然后,我们将讨论这个定义的每个部分。最后,我们将会仔细研究基础索引允许我们在不复制的情况下引用其内置数据的重要性。
-**Definition: Basic Indexing**: +**定义:基础索引**: -Given an $N$-dimensional array, `x`, `x[index]` invokes **basic indexing** whenever `index` is a *tuple* containing any combination of the following types of objects: +设 $N$ 维数组 `x`,`x[index]` 使用**基础索引**的时候是当 `index` 是一个含有以下任何对象类型组合的*元组*: -- integers -- [slice](http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Slicing) objects -- [Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis) objects -- [numpy.newaxis](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html#Inserting-Size-1-Dimensions-into-An-Array) objects +- 整数 +- [切片](http://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Slicing)对象 +- [省略号](https://docs.python.org/3/library/constants.html#Ellipsis)(ellipsis)对象 +- [numpy.newaxis](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html#Inserting-Size-1-Dimensions-into-An-Array)对象 -Accessing the contents of an array via basic indexing *does not create a copy of those contents*. Rather, a "view" of the same underlying data is produced. +通过基础索引来访问数组对象*并不会复制数组的成员*。反而,这会创建一个内置数据的“视阈”。
-### Indexing with Integers and Slice Objects -Our discussion of [accessing data along multiple dimensions of a NumPy array](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.html) already provided a comprehensive rundown on the use of integers and slices to access the contents of an array. According to the preceding definition, *these were all examples of basic indexing*. +### 用整数和切片对象索引 +我们在[访问数组多维度的内容](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/AccessingDataAlongMultipleDimensions.html)一节已经提供了完整的使用整数和切片来访问数组成员的教程。根据之前的定义,*这些都是基础索引的范例*。 -To review the material discussed in that section, recall that one can access an individual element or a "subsection" of an $N$-dimensional array by specifying $N$ integers or slice-objects, or a combination of the two. We also saw that, when supplied fewer-than $N$ indices, NumPy will automatically "fill-in" the remaining indices with trailing slices. Keep in mind that the indices start at 0, such that the 4th column in `x` corresponds to column-3. +作为那一节讨论的内容的复习,请回忆,你可以通过提供 $N$ 个整数或切片对象或两种混合来选中 $N$ 维数组的单个成员或“子部分”。我们也了解了当你提供少于 $N$ 个索引时NumPy会自动将剩余位置用末尾切片“填满”。请记住,索引从0开始,所以 `x` 的第4列对应着列3。 -```python -# Accessing the element located -# at row-1, last-column of `x` +```python +# 访问 `x` 行1,最后一列的成员 >>> x[1, -1] 8 -# Access the subarray of `x` -# contained within the first two rows -# and the first three columns +# 访问 `x` 在前两行和前三列中的子数组 >>> x[:2, :3] array([[-5, 2, 0], [-1, 9, 3]]) -# NumPy fills in "trailing" slices -# if we don't supply as many indices -# as there are dimensions in that array ->>> x[0] # equivalent to x[0, :] +# 当我们提供索引数少于维度时,NumPy会自动 +# 用“末尾”切片填满空余的位置 +>>> x[0] # 等值于 x[0, :] array([-5, 2, 0, -7]) ``` -Recall that the familiar [slicing](http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Slicing) syntax actually forms `slice` objects "behind the scenes". +请回忆,我们熟悉的[切片](http://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Slicing)语法其实在“幕后”会创建 `slice` 对象。 ```python -# Reviewing the `slice` object +# 复习 `slice` 对象 -# equivalent: x[:2, :3] +# 等值于:x[:2, :3] >>> x[slice(None, 2), slice(None, 3)] array([[-5, 2, 0], [-1, 9, 3]]) ``` -### Using a Tuple as an N-dimensional Index -According to its definition, we must supply our array-indices as a tuple in order to invoke basic indexing. As it turns out, we have been forming tuples of indices all along! That is, every time that we index into an array using the syntax `x[i, j, k]`, we are actually forming a [tuple](http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Tuples) containing those indices. That is, `x[i, j, k]` is equivalent to `x[(i, j, k)]`. +### 将元组作为N维索引使用 +根据基础索引的定义,我们必须将我们的数组索引以元组的形式来提供才能使用基础索引。事实上,我们一直以来都在使用索引元组!也就是说,每当我们使用语法 `x[i, j, k]` 来索引一个数组时,我们其实是在创建一个包含这些索引的[元组](http://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html#Tuples)。也就是说,`x[i, j, k]` 等值于 `x[(i, j, k)]`。 -`x[i, j, k]` forms the tuple `(i, j, k)` and passes that to the array's "get-item" mechanism. Thus, `x[0, 3]` is equivalent to `x[(0, 3)]`. +`x[i, j, k]` 将创建元组 `(i, j, k)` 并将其输入到数组的“获取成员”功能中。因此, `x[0, 3]` 等值于 `x[(0, 3)]`。 ```python -# N-dimensional indexing utilizes tuples: -# `x[i, j, k]` is equivalent to `x[(i, j, k)]` +# 使用元组的N维索引 +# `x[i, j, k]` 等值于 `x[(i, j, k)]` -# equivalent: x[1, -1] +# 等值于:x[1, -1] >>> x[(1, -1)] 8 -# equivalent: x[:2, :3] +# 等值于:x[:2, :3] >>> x[(slice(None, 2), slice(None, 3))] array([[-5, 2, 0], [-1, 9, 3]]) -# equivalent: x[0] +# 等值于:x[0] >>> x[(0,)] array([-5, 2, 0, -7]) ``` -All objects used in this "get-item" syntax are packed into a tuple. For instance, `x[0, (0, 1)]` is equivalent to `x[(0, (0, 1))]`. You may be surprised to find that this is a valid index. However, see that *it does not invoke basic indexing*; the index used here is a tuple that contains an integer *and another tuple*, which is not permitted by the rules of basic indexing. +所有在这个“获取成员”语法中使用的对象都会被打包成一个元组。比如说,`x[0, (0, 1)]` 等值于 `x[(0, (0, 1))]`。你可能会惊讶于这是合法索引这一事实。但是,请注意,*它并不使用基础索引*;在这里使用的索引是包含一个整数*和另一个数组*的元组,所以这不符合基础索引的规则。 -Finally, note that the rules of basic indexing specifically call for a *tuple* of indices. Supplying a list of indices triggers advanced indexing rather than basic indexing! +最后,请注意,基础索引的规则只允许索引*元组*。提供索引列表会导致你使用进阶索引,而不是基础索引! ```python -# basic indexing specifically requires a tuple +# 基础索引只接受元组 >>> x[(1, -1)] 8 -# indexing with a list triggers advanced indexing +# 使用列表来索引会导致你使用进阶索引 >>> x[[1, -1]] array([[-1, 9, 3, 8], [-3, -3, 4, 6]]) @@ -144,23 +138,23 @@ array([[-1, 9, 3, 8], -### Ellipsis and Newaxis objects -Recall from our discussion of broadcasting, that the `numpy.newaxis` object can be passed as an index to an array, in order to [insert a size-1 dimension into the array](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html#Inserting-Size-1-Dimensions-into-An-Array). +### 省略号和newaxis对象 +根据从之前对广播的讨论,`numpy.newaxis` 对象可以作为数组的索引使用来[向数组插入大小为1的维度](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html#Inserting-Size-1-Dimensions-into-An-Array)。 ```python -# inserting size-1 dimensions with `np.newaxis` +# 通过 `np.newaxis` 插入大小为1的维度 >>> x.shape (3, 4) >>> x[np.newaxis, :, :, np.newaxis].shape (1, 3, 4, 1) -# forming the index as an explicit tuple +# 使用显式的元组来当索引 >>> x[(np.newaxis, slice(None), slice(None), np.newaxis)].shape (1, 3, 4, 1) ``` -We can also use the built-in `Ellipsis` object in order to insert slices into our index such that the index has as many entries as the array has dimensions. In the same way that `:` can be used to represent a `slice` object, `...` can be used to represent an `Ellipsis` object. +我们也可以使用内置的 `Ellipsis`(省略号)对象来在索引中插入切片来强制让索引填满和数组维度一样多的索引。就像 `:` 可以用来代表 `slice` 对象一般,`...` 也可以用来代表 `Ellipsis` 对象。 ```python >>> y = np.array([[[ 0, 1, 2, 3], @@ -172,31 +166,31 @@ We can also use the built-in `Ellipsis` object in order to insert slices into ou ... [[16, 17, 18, 19], ... [20, 21, 22, 23]]]) -# equivalent: `y[:, :, 0]` +# 等值于:`y[:, :, 0]` >>> y[..., 0] array([[ 0, 4], [ 8, 12], [16, 20]]) -# using an explicit tuple +# 使用显式的元组索引 >>> y[(Ellipsis, 0)] array([[ 0, 4], [ 8, 12], [16, 20]]) -# equivalent: `y[0, :, 1]` +# 等值于:`y[0, :, 1]` >>> y[0, ..., 1] array([1, 5]) ``` -An index cannot possess more than one `Ellipsis` entry. This can be extremely useful when working with arrays of varying dimensionalities. To access column-0 along all dimensions of an array, `z`, would look like `z[:, 0]` for a 2D array, `z[:, :, 0]` for a 3D array, and so on. `z[..., 0]` succinctly encapsulates all iterations of this. +一个索引不能拥有超过一个 `Ellipsis` 在其中。这在你处理不同维度的数组时极其有用。来访问某数组 `z` 的所有维度的列0,如果是2维数组会是 `z[:, 0]`,如果是3维数组是 `z[:, :, 0]`,以此重复。`z[..., 0]` 则能够简短地包装这里所有的迭代。
-**Takeaway:** +**经验**: -Basic indexing is triggered whenever a tuple of: integer, `slice`, `numpy.newaxis`, and/or `Ellipsis` objects, is used as an index for a NumPy array. An array produced via basic indexing is a *view* of the same underlying data as the array that was indexed into; no data is copied through basic indexing. +基础索引将在你向NumPy数组输入的索引是一个元组,其成员为:整数,`slice`,`numpy.newaxis`,或 `Ellipsis` 对象。通过基础索引返回的数组是原本数组内置数据的一个*视阈*;基础索引并不会导致任何数据被复制。
@@ -204,9 +198,9 @@ Basic indexing is triggered whenever a tuple of: integer, `slice`, `numpy.newaxi
-**Reading Comprehension: Ellipsis** +**阅读理解:省略号** -Given a $N$-dimensional array, `x`, index into `x` such that you axis entry-0 of axis-0, the last entry of axis-$N-1$, slicing along all intermediate dimensions. $N$ is at least $2$. +设 $N$ 维数组 `x`,索引 `x` 来获取轴0的第一个成员,轴 $N-1$ 的最后一个成员,并切片中间所有维度。$N$ 至少为 $2$。
@@ -214,9 +208,9 @@ Given a $N$-dimensional array, `x`, index into `x` such that you axis entry-0 of
-**Reading Comprehension: Basic Indexing** +**阅读理解:基础索引** -Given a shape-(4, 3) array, +设形状为 (4, 3) 的数组: ```python >>> arr = np.array([[ 0, 1, 2, 3], @@ -224,7 +218,7 @@ Given a shape-(4, 3) array, ... [ 8, 9, 10, 11]]) ``` -which of the following indexing schemes perform basic indexing? That is, in which instances does the index satisfy the rules of basic indexing? +以下哪些索引方法使用基础索引?也就是说,以下哪些索引满足了基础索引的规则? - `arr[0]` - `arr[:-1, 0]` @@ -239,27 +233,25 @@ which of the following indexing schemes perform basic indexing? That is, in whic -## Producing a View of an Array -As stated above, using basic indexing does not return a copy of the data being accessed, rather it produces a *view* of the underlying data. NumPy provides the function `numpy.shares_memory` to determine if two arrays refer to the same underlying data. +## 创建数组视阈 +如上所述,使用基础索引不会返回访问数据的复制品;反而,它会返回内置数据的一个*视阈*(view)。NumPy提供了 `numpy.shares_memory` 函数来检查两个数组是否引用了相同的内置数据。 ```python >>> z = np.array([[ 3.31, 4.71, 0.4 ], ... [ 0.21, 2.85, 3.21], ... [-3.77, 4.53, -1.15]]) -# `subarray` is column-0 of `z`, via -# basic indexing +# `subarray` 是通过基础索引获得的 `z` 的列0 >>> subarray = z[:, 0] >>> subarray array([ 3.31, 0.21, -3.77]) -# `subarray` is a view of the array data -# referenced by `z` +# `subarray` 是 `z` 的数组数据的一个视阈 >>> np.shares_memory(subarray, z) True ``` -A single number returned by basic indexing *does not* share memory with the parent array. +通过基础索引返回的单个数字*不*和父数组共享内存。 ```python >>> z[0, 0] 3.31 @@ -267,10 +259,10 @@ A single number returned by basic indexing *does not* share memory with the pare >>> np.shares_memory(z[0, 0], z) False ``` -The function `numpy.copy` can be used to create a copy of an array, such that it no longer shares memory with any other array. +函数 `numpy.copy` 可以用来复制数组,使得返回的数组并不和输入的数组共享内存。 ```python -# creating a distinct copy of an array +# 创建一个数组的复制品 >>> new_subarray = np.copy(subarray) >>> new_subarray array([ 3.31, 0.21, -3.77]) @@ -279,24 +271,24 @@ array([ 3.31, 0.21, -3.77]) False ``` -Utilizing an array in a mathematical expression involving the arithmetic operators (`+, -, *, /, //, **`) returns an entirely distinct array, that does not share memory with the original array. +通过算数操作符(`+, -, *, /, //, **`)使用的数组会返回完全不同,和原本数组不共享内存的数组。 ```python -# mathematical expressions like `subarray + 2` -# produce distinct arrays, not views +# 像 `subarray + 2` 这样的数学表达式将创建不同的数组, +# 而不是视阈 >>> np.shares_memory(subarray + 2, subarray) False ``` -Thus updating a variable `subarray` via `subarray = subarray + 2` does *not* overwrite the original data referenced by `subarray`. Rather, `subarray + 2` assigns that new array to the variable `subarray`. NumPy does provide mechanisms for performing mathematical operations to directly update the underlying data of an array without having to create a distinct array. We will discuss these mechanisms in the next subsection. +因此,通过 `subarray = subarray + 2` 更新 `subarray` *不*会重现 `subarray` 引用的原本数据。反而,`subarray + 2` 会将新创建的数组赋值给变量 `subarray`。NumPy也提供了直接更新原本数组内置数据而不创建新数组的数学操作。我们将在下一小节讨论这些功能。
-**Reading Comprehension: Views** +**阅读理解:视阈** -Given, +设: ```python x = np.array([[ 0, 1, 2, 3], @@ -304,7 +296,7 @@ x = np.array([[ 0, 1, 2, 3], [ 8, 9, 10, 11]]) ``` -Which of the following expressions create views of `x`? That is, in which cases do `x` and the created variable reference the same underlying array data? Check your work by using `np.shares_memory`. +以下哪些表达式创建了 `x` 的视阈?也就是说,在哪些情况下 `x` 和被创建的变量引用着相同的内置数组数据?使用 `np.shares_memory` 来检查你的答案。 - `a1 = x` - `a2 = x[0, 0]` @@ -318,19 +310,19 @@ Which of the following expressions create views of `x`? That is, in which cases
-## Augmenting the Underlying Data of an Array -Because basic indexing produces a *view* of an array's underlying data, we must take time to understand the ways in which we can *augment* that underlying data, versus performing operations that produce an array with distinct data. Here we will see that: +## 增强数组的内置数据 +因为基础索引返回数组内置数据的*视阈*,我们需要花些时间来理解,相比于会创建有着不同数据的新数组的操作,我们可以通过哪些方式来*增强*(augment)输入的内置数据。我们将在其看到: -- in-place assignments -- augmented assignments -- NumPy functions with the `out` argument +- 原地赋值 +- 增强赋值 +- 提供 `out` 参数的NumPy函数 -can all be used to augment array data in-place. +可以用来原地(in-place)增强数组的数据。 -### In-Place Assignments +### 原地赋值 -The assignment operator, `=`, can be used to update an array's data in-place. Consider the array `a`, and its view `b`. +赋值操作符 `=` 可以被用来原地更新数组的数据。设数组 `a` 和它的视阈 `b`。 ```python >>> a = np.array([0, 1, 2, 3, 4]) >>> b = a[:] @@ -338,12 +330,12 @@ The assignment operator, `=`, can be used to update an array's data in-place. Co True ``` -Assigning a new array to `a` simply changes the data that `a` references, divorcing `a` and `b`, and leaving `b` unchanged. +为 `a` 赋值一个新数组仅仅改变了 `a` 引用的数据,并使得 `a` 和 `b` 没有关联,而并不会修改 `b` 。 ```python -# `a` is now assigned to reference a distinct array +# `a` 在赋值后引用另外一个数组 >>> a = np.array([0, -1, -2, -3, -4]) -# `b` still references the original data +# `b` 依然引用着原本的数据 >>> b array([0, 1, 2, 3, 4]) @@ -351,22 +343,22 @@ array([0, 1, 2, 3, 4]) False ``` -Performing an assignment on a *view* of `a`, i.e. `a[:]`, instructs NumPy to perform the assignment to replace `a`'s data in-place. +为 `a` 的视阈,也就是 `a[:]`,进行操作会告诉NumPy去通过赋值原地代替 `a` 的数据。 ```python -# reinitialize `a` and `b`. -# `b` is again a view of `a` +# 重新初始化`a` 和 `b`。 +# `b` 任然是 `a` 的视阈 >>> a = np.array([0, 1, 2, 3, 4]) >>> b = a[:] -# assigning an array to a *view* of `a` -# causes NumPy to update the data in-place +# 向 `a` 的*视阈*赋值一个新数组会导致NumPy原地 +# 更新其数据 >>> a[:] = np.array([0, -1, -2, -3, -4]) >>> a array([ 0, -1, -2, -3, -4]) -# `b` a view of the same data, thus -# it is affected by this in-place assignment +# `b` 任然是相同数据的视阈,因此它受到这个原地赋值 +# 的影响 >>> b array([ 0, -1, -2, -3, -4]) @@ -374,7 +366,7 @@ array([ 0, -1, -2, -3, -4]) True ``` -This view-assignment mechanism can be used update a subsection of an array in-place. +这个视阈赋值功能可以用来原地更新数组的一部分。 ```python >>> p = np.array([[ 0, 1, 2, 3], @@ -382,47 +374,44 @@ This view-assignment mechanism can be used update a subsection of an array in-pl ... [ 8, 9, 10, 11]]) >>> q = p[0, :] -# Assign row-0, column-0 the value -40 -# and row-0, column-2 the value -50 +# 设行0,列0为值-40 +# 设行0,列2为值-50 >>> p[0, ::2] = (-40, -50) -# broadcast-assign -1 to a subsection of `p` +# 为 `p` 的一部分广播赋值-1 >>> p[1:, 2:] = -1 >>> p array([[-40, 1, -50, 3], [ 4, 5, -1, -1], [ 8, 9, -1, -1]]) ``` -Again, this updates the underlying data, and thus all views of this data reflect this change. +同样的,这将会更新内置的数据,所以这数据的所有视阈都会反映这个变化。 ```python -# `q` is still a view of row-0 of `p` +# `q` 依然是 `p` 第0行的视阈 >>> q array([-40, 1, -50, 3]) ``` -### Augmented Assignments -Recall from our discussion of basic mathematical expressions in Python, that [augmented assignment expressions](http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Augmented-Assignment-Statements) provide a nice shorthand notation for updating the value of a variable. For example, the assignment expression `x = x + 5` can be rewritten using the augmented assignment `x += 5`. +### 增强赋值 +我们对Python基础数学表达式的讨论提到了[增强赋值语句](http://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Augmented-Assignment-Statements)(augmented assignment statement)。它为我们提供了一个方便的更新变量值的简写语法。比如说,赋值表达式 `x = x + 5` 可以通过增强赋值来重写为 `x += 5`。 -While `x += 5` is truly only a shorthand in the context of basic Python objects (integer,s floats, etc.), *augmented assignments on NumPy arrays behave fundamentally different than their long-form counterparts*. Specifically, they directly update the underlying data referenced by the updated array, rather than creating a distinct array, thus affecting any arrays that are views of that data. We will demonstrate this here. +虽然 `x += 5` 在处理Python基础对象(整数,浮点数,等等)时真的只是一个简写,*但是NumPy数组的增强赋值和它们更长的版本有着根本性不同的行为*。具体来讲,它们会直接更新数组引用的内置数据,而不会创建一个新的不同的数组。因此这会影响所有该数组的视阈。我们在以下演示。 ```python -# Demonstrating that augmented assignments on NumPy -# arrays update the underlying data reference by that -# array. +# 演示对NumPy数组的增强赋值会更新该数组引用的内置数据。 >>> a = np.array([[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]]) -# `b` and `c` are both views of row-0 of `a`, via basic indexing +# `b` 和 `c` 都是通过基础索引创建的 `a` 第0行的视阈 >>> b = a[0] >>> c = a[0] >>> np.shares_memory(a, b) and np.shares_memory(a, c) True -# updating `b` using a mathematical expression creates -# a distinct array, which is divorced from `a` and `c` +# 使用数学表达式更新 `b` 会创建一个新数组并消除 `a` 和 `c` 的关系 >>> b = b * -1 >>> b array([ 0, -1, -2, -3]) @@ -430,8 +419,7 @@ array([ 0, -1, -2, -3]) >>> np.shares_memory(a, b) False -# updating `c` using augmented assignment updates the -# underlying data that `c` is a view of +# 使用增强赋值更新 `c` 会更新 `c` 引用的内置数据 >>> c *= -2 >>> c array([ 0, -2, -4, -6]) @@ -439,8 +427,7 @@ array([ 0, -2, -4, -6]) >>> np.shares_memory(a, c) True -# note that this update is reflected in `a` as well, -# as it still shares memory with `c` +# 请注意,这个更新也会在 `a` 中反映,因为它依然和 `c` 共享内存 >>> a array([[ 0, -2, -4, -6], [ 4, 5, 6, 7], @@ -449,25 +436,23 @@ array([[ 0, -2, -4, -6], -### Specifying `out` to Perform NumPy Operations In-Place -There is no reason why we should only be able to augment data using arithmetic operations. Indeed, [NumPy's various mathematical functions](https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html#NumPy%E2%80%99s-Mathematical-Functions) have an optional keyword argument, `out`, which can be used to specify where to "store" the result of the mathematical operation. By default, the operation will create a distinct array in memory, leaving the input data unaffected. +### 提供 `out` 来原地进行NumPy操作 +我们没有任何理由只能在算数操作时可以原地更新数据。[NumPy的各种数学函数](https://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html#NumPy%E2%80%99s-Mathematical-Functions)提供了一个可选的关键词参数 `out` 来提供“储存”数学运算结果的地方。默认的情况下,这个操作会在内存中创建一个不同的新数组并不修改输入数据。 ```python -# Specifying the 'out' argument in a `numpy.exp` -# to augment the data of an array +# 在 `numpy.exp` 中提供 'out' 参数来原地更新数组数据 -# `b` is a view of `a` +# `b` 是 `a` 的视阈 >>> a = np.array([0., 0.2, 0.4, 0.6, 0.8, 1.]) >>> b = a[:] >>> np.shares_memory(a, b) True -# specifying 'out=a' instructs NumPy -# to overwrite the data referenced by `a` +# 提供 'out=a' 将会告诉NumPy去覆盖 `a` 引用的数据 >>> np.exp(a, out=a) array([ 1., 1.22140276, 1.4918247, 1.8221188, 2.22554093, 2.71828183]) -# `b` is still a view of the now-augmented data +# `b` 依然是现在更新过的数据的视阈 >>> b array([ 1., 1.22140276, 1.4918247, 1.8221188, 2.22554093, 2.71828183]) ``` @@ -475,13 +460,13 @@ array([ 1., 1.22140276, 1.4918247, 1.8221188, 2.22554093, 2.71828183]) -### Benefits and Risks of Augmenting Data In-Place -It is critical to understand the relationship between arrays and the underlying data that they reference. *Operations that augment data in-place are more efficient than their counterparts that must allocate memory for a new array.* That is, an expression like `array += 3` is more efficient than `array = array + 3`. +### 原地增强数据的好处和危险 +理解数组和它们引用的内置数据的关系是极其重要的。*原地增强数据的操作比它们必须为创建新数组来分配内存的版本更加高效*。也就是说,像 `array += 3` 的表达式比 `array = array + 3` 更加高效。 -That being said, to *unwittingly* augment the data of an array, and thus affect all views of that data, is a big mistake; this produces hard-to-find bugs in the code of novice NumPy users. See that the following function, `add_3`, will change the data of the input array. +虽然如此,*在不知情的情况下*一不小心原地更新数组数据并影响数组所有视阈则会是一个巨大的错误;这将导致NumPy新手用户代码中出现难以查清的bug。以下函数 `add_3` 将会修改输入数组的数据。 ```python -# updating an array in-place within a function +# 在函数内原地更新数组 def add_3(x): x += 3 return x @@ -491,12 +476,12 @@ def add_3(x): >>> y array([3, 4, 5]) -# `x` is updated each time `f(x)` is called +# `x` 在 `add_3(x)` 被调用时都会被更新 >>> x array([3, 4, 5]) ``` -This is hugely problematic unless you intended for `add_3` to affect the input array. To remedy this, you can simply begin the function by making a copy of the input array; afterwards you can freely augment this copied data. +除非你本意就是让 `add_3` 修改输入数组,这样做的问题很大。为了修补这个问题,你可以在函数开头复制输入数组;在这之后,你可以随意地使用增强语句原地更新复制过的数据。 ```python def add_3(x): x = np.copy(x) @@ -508,9 +493,9 @@ def add_3(x):
-**Reading Comprehension: Augmenting Array Data In-Place** +**阅读理解:原地增强数组数据** -Given, +设: ```python x = np.array([[ 0., 1., 2., 3.], @@ -520,7 +505,7 @@ x = np.array([[ 0., 1., 2., 3.], y = x[0, :] ``` -Which of the following expressions updates the data originally referenced by `x`? +以下哪些表达式会更新 `x` 原本引用的数据? ```python # 1. @@ -575,48 +560,48 @@ Which of the following expressions updates the data originally referenced by `x`
-**Takeaway:** +**经验**: -Assignments to views of an array, augmented assignments, and NumPy functions that provide an `out` argument, are all methods for augmenting the data of an array in-place. This will affect any arrays that are views of that data. Furthermore, these in-place operations are more efficient than their counterparts that allocate memory for a new array. That being said, in-place data augmentation must not be used haphazardly, for this will inevitably lead to treacherous bugs in one's code. +赋值数组视阈,增强赋值语句,和提供 `out` 参数的NumPy函数都是原地增强数组数据的方法。这将会影响任何相同数据的视阈。同时,这些原地更新的操作比它们需要分配内存来创建新数组的版本更加高效。虽然如此,请不要胡乱使用原地数据增强,因为这早晚在你代码中会导致恶性的bug。
-## Links to Official Documentation +## 官方说明文档链接 -- [Basic indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#indexing) -- [Definition of 'view'](https://docs.scipy.org/doc/numpy/glossary.html#term-view) +- [基础索引](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#indexing) +- [“视阈”的定义](https://docs.scipy.org/doc/numpy/glossary.html#term-view) -## Reading Comprehension Solutions +## 阅读理解答案: -**Ellipsis: Solution** +**省略号:解** -Given a $N$-dimensional array, `x`, index into `x` such that you axis entry-0 of axis-0, the last entry of axis-$(N-1)$, slicing along all intermediate dimensions. $N$ is at least $2$. +设 $N$ 维数组 `x`,索引 `x` 来获取轴0的第一个成员,轴 $N-1$ 的最后一个成员,并切片中间所有维度。$N$ 至少为 $2$。 -Using an `Ellipsis` object in the index allows us to signal NumPy to insert the slices along the $N - 2$ intermediate axis of `x`: +在这个索引中使用 `Ellipsis` 对象将允许我们告诉NumPy在 `x` 中间的 $N - 2$ 个轴中插入切片: -`x[0, ..., -1]` or `x[0, Ellipsis, -1]` +`x[0, ..., -1]` 或 `x[0, Ellipsis, -1]` -**Basic Indexing: Solution** +**基础索引:解** -In which instances does the index used satisfy the rules of basic indexing? +以下哪些的索引满足了基础索引的规则? - `arr[0]` ✔ - `arr[:-1, 0]` ✔ - `arr[(2, 3)]` ✔ - - `arr[[2, 0]]` ✘ (index is a `list`, not a `tuple`) - - `arr[np.array([2, 0])]` ✘ (index is a `numpy.ndarray`, not a `tuple`) - - `arr[:, (2, 3)]` ✘ (index contains a tuple; only `int`, `slice`, `np.newaxis`, `Ellipsis` allowed) + - `arr[[2, 0]]` ✘(索引是一个 `list`,而不是 `tuple`) + - `arr[np.array([2, 0])]` ✘(索引是一个 `numpy.ndarray`,而不是 `tuple`) + - `arr[:, (2, 3)]` ✘(索引包含了一个元组;只有`int`,`slice`,`np.newaxis`,`Ellipsis` 是被允许的) - `arr[slice(None), ...]` ✔ - `arr[(np.newaxis, 0, slice(1, 2), np.newaxis)]` ✔ -**Views: Solution** +**视阈:解** -Given, +设: ```python x = np.array([[ 0, 1, 2, 3], @@ -624,22 +609,22 @@ x = np.array([[ 0, 1, 2, 3], [ 8, 9, 10, 11]]) ``` -Which of the following expressions create views `x`? That is, in which cases do `x` and the created variable reference the same underlying array data? Check your work by using `np.shares_memory`. +以下哪些表达式创建了 `x` 的视阈?也就是说,在哪些情况下 `x` 和被创建的变量引用着相同的内置数组数据?使用 `np.shares_memory` 来检查你的答案。 - `a1 = x` ✔ -- `a2 = x[0, 0]` ✘; when basic indexing returns a single number, that number does not share memory with the parent array. +- `a2 = x[0, 0]` ✘;当基础索引返回单个数字时,这个数字不和父数组共享内存。 - `a3 = x[:, 0]` ✔ -- `a4 = x[:, 0] + np.array([-1, -2, -3])` ✘; arithmetic operations on NumPy arrays create distinct arrays by default. -- `a5 = np.copy(x[:, 0])` ✘; `numpy.copy` informs NumPy to create a distinct copy of an array. +- `a4 = x[:, 0] + np.array([-1, -2, -3])` ✘;对NumPy数组的算数操作默认创建不同的数组。 +- `a5 = np.copy(x[:, 0])` ✘;`numpy.copy` 指示NumPy去创建数组的复制品。 - `a6 = x[np.newaxis]` ✔ - `a7 = x.reshape(2, 3, 2)` ✔ -- `a8 = 2 + x` ✘; arithmetic operations on NumPy arrays create distinct arrays by default. +- `a8 = 2 + x` ✘;对NumPy数组的算数操作默认创建不同的数组。 -**Augmenting Array Data In-Place: Solution** +**原地增强数组数据:解** -Given, +设: ```python x = np.array([[ 0., 1., 2., 3.], @@ -649,7 +634,7 @@ x = np.array([[ 0., 1., 2., 3.], y = x[0, :] ``` -Which of the following expressions updates the data originally referenced by `x`? +以下哪些表达式会更新 `x` 原本引用的数据? ```python # 1. diff --git a/Python/Module3_IntroducingNumpy/Broadcasting.md b/Python/Module3_IntroducingNumpy/Broadcasting.md index 41a8f5a..5a566f6 100644 --- a/Python/Module3_IntroducingNumpy/Broadcasting.md +++ b/Python/Module3_IntroducingNumpy/Broadcasting.md @@ -4,44 +4,44 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Numpy array broadcasting, Difficulty: Medium, Category: Section :keywords: broadcasting, vectorization, rules, mismatched shapes, distances -``` + -# Array Broadcasting -NumPy provides a mechanism for performing mathematical operations on arrays of *unequal* shapes: +# 数组广播 +NumPy提供了用来广播(broadcast)对*不同*形状的数组进行数学操作的功能: ```python >>> import numpy as np -# a shape-(3, 4) array +# 形状为 (3, 4) 的数组 >>> x = np.array([[-0. , -0.1, -0.2, -0.3], ... [-0.4, -0.5, -0.6, -0.7], ... [-0.8, -0.9, -1. , -1.1]]) -# a shape-(4,) array +# 形状为 (4,) 的数组 >>> y = np.array([1, 2, 3, 4]) -# multiplying a shape-(4,) array with a shape-(3, 4) array -# `y` is multiplied by each row of `x` +# 使用形状为 (4,) 的数组乘到形状为 (3, 4) 的数组 +# `y` 被 `x` 的每一行乘上 >>> x * y array([[-0. , -0.2, -0.6, -1.2], [-0.4, -1. , -1.8, -2.8], [-0.8, -1.8, -3. , -4.4]]) ``` -In effect, NumPy treated `y` as if its contents had been broadcasted along a new dimension, such that `y` was a shape-(3, 4) 2D array, which makes it compatible for multiplying with `x`: +从结果上讲,NumPy将 `y` 在一个新的维度广播,使其成为形状是 (3, 4) 的二维数组,这样它的形状就和 `x` 相对应,支持相乘了: \begin{equation} \left( \begin{array}{*{3}{X}} @@ -68,16 +68,14 @@ In effect, NumPy treated `y` as if its contents had been broadcasted along a new \ \end{equation} -It is important to note that NumPy doesn't really create this broadcasted version of `y` behind the scenes; it is able to do the necessary computations without having to redundantly copy its contents into a shape-(3,4) array. Doing so would be a waste of memory and computation. That being said, this replication process conveys exactly the mathematics of broadcast operations between arrays; thus the preceding diagram reflects how you should always envision broadcasting. - +请注意,NumPy并不会真的在幕后创建这个广播过的 `y` 版本;NumPy能够在不浪费地将它的成员复制到形状为 (3,4) 的数组的情况下进行必须的运算。因为这么做会浪费内存和计算时间。虽然如此,这个不存在的复制过程能够表达数组之间的数学运算,所以之前的图表假装这个复制过程存在。你在也可以假装内容被复制了来方便理解广播的结果。 -Broadcasting is not reserved for operations between 1-D and 2-D arrays, and furthermore both arrays in an operation may undergo broadcasting. That being said, not all pairs of arrays are broadcast-compatible. +广播不仅仅作用域在1维和2维数组之间的操作,因此有些时候操作中的两个数组都需要被广播。虽然如此,但是不是所有对的数组都可以通过广播来兼容的(叫做广播不兼容——broadcast-incompatible)。 ```python -# Broadcast multiplications between a -# shape-(3, 1, 2) array and a shape-(3, 1) -# array. +# 广播形状为 (3, 1, 2) 的数组和形状为 (3, 1) +# 的数组的乘法。 >>> x = np.array([[[0, 1]], ... ... [[2, 3]], @@ -88,8 +86,8 @@ Broadcasting is not reserved for operations between 1-D and 2-D arrays, and furt ... [ 1], ... [-1]]) -# shape-(3, 1, 2) broadcast-multiply with -# shape-(3, 1) produces shape-(3, 3, 2) +# 形状 (3, 1, 2) 广播相乘形状 (3, 1) +# 返回形状 (3, 3, 2) >>> x * y array([[[ 0, 0], [ 0, 1], @@ -103,8 +101,8 @@ array([[[ 0, 0], [ 4, 5], [-4, -5]]]) -# an example of broadcast-incompatible arrays -# a shape-(2,) array with a shape-(3,) array +# 一个广播不兼容数组对的例子 +# 形状为 (2,) 的数组和形状为 (3,) 的数组 >>> np.array([1, 2]) * np.array([0, 1, 2]) ValueError: operands could not be broadcast together with shapes (2,) (3,) ``` @@ -112,43 +110,43 @@ ValueError: operands could not be broadcast together with shapes (2,) (3,)
-**Definition: Array Broadcasting** +**定义:数组广播** -Array Broadcasting is a mechanism used by NumPy to permit vectorized mathematical operations between arrays of unequal, but compatible shapes. Specifically, an array will be treated as if its contents have been replicated along the appropriate dimensions, such that the shape of this new, higher-dimensional array suits the mathematical operation being performed. +数组广播(array broadcasting)是NumPy用来支持形状不同但兼容的多个数组之间的矢量化数学操作的功能。具体来讲,NumPy会假装数组的内容在某个合适的维度被复制,使得这个复制出来,更高维度的数组能够完成这里的数学操作。
-We will now summarize the rules that determine if two arrays are broadcast-compatible with one another, and what the shape of the resulting array will be after the mathematical operation between the two arrays is performed. +现在我们将总结检查两个数组是否广播兼容的规则,以及在进行数学操作后得到的数组的形状。 -## Rules of Broadcasting -Array broadcasting cannot accommodate arbitrary combinations of array shapes. For example, a (7,5)-shape array is incompatible with a shape-(11,3) array. Trying to add two such arrays would produce a `ValueError`. The following rules determine if two arrays are broadcast-compatible: +## 广播的规则 +数组广播并不能支持任何组合的数组形状。比如说,一个形状为 (7,5) 的数组就不和形状为 (11,3) 的数组兼容。试图将这两个数组相加会导致一个 `ValueError`。以下规则可以用来决定两个数组是否广播兼容:
-**Definition: Rules of Broadcasting**: +**定义:广播的规则**: -To determine if two arrays are broadcast-compatible, align the entries of their shapes such that their trailing dimensions are aligned, and then check that each pair of aligned dimensions satisfy either of the following conditions: +为检测两个数组是否广播兼容,将两个数组的形状靠尾对应,然后检查每对对应的维度是否满足以下条件之一: -- the aligned dimensions have the same size -- one of the dimensions has a size of 1 +- 对应的维度大小一样 +- 其中一个维度的大小是1 -The two arrays are broadcast-compatible if either of these conditions are satisfied for each pair of aligned dimensions. +如果每对对应的维度都满足以上之一,那么这两个数组广播兼容。
- -Note that it is okay to have one array with a higher-dimensionality and thus to have "dangling" leading dimensions. Any size-1 dimension or "missing" dimension will be filled-in by broadcasting the content of that array. -Considering the example from the preceding subsection, let's see that the shape-(4,3) and shape-(3,) arrays satisfy these rules for broadcast-compatibility: +请注意,如果一个数组的维度更高并导致前面有些维度没有和另外一个数组对应,这是没有问题的。任何大小为1的维度或”缺失“的维度都会通过广播来填充。 + +请考虑前一小节的范例。请根据以上规则思考为什么形状为 (4,3) 和形状为 (3,) 的数组满足广播兼容的规则: ``` array-1: 4 x 3 array-2: 3 result-shape: 4 x 3 ``` -Let's look an assortment of pairs of array-shapes and see whether or not they are broadcast-compatible: +让我们来考虑各种数组形状的对并理解它们为何广播(不)兼容: ``` array-1: 8 @@ -157,7 +155,7 @@ result-shape: 5 x 2 x 8 array-1: 5 x 2 array-2: 5 x 4 x 2 -result-shape: INCOMPATIBLE +result-shape: 不兼容 array-1: 4 x 2 array-2: 5 x 4 x 2 @@ -173,26 +171,25 @@ result-shape: 5 x 9 x 3 x 2 array-1: 1 x 3 x 2 array-2: 8 x 2 -result-shape: INCOMPATIBLE +result-shape: 不兼容 array-1: 2 x 1 array-2: 1 result-shape: 2 x 1 ``` - -NumPy provides the function [broadcast_to](https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html#numpy.broadcast_to), which can be used to broadcast an array to a specified shape. This can help us build our intuition for broadcasting. Let's broadcast a shape-(3,4) array to a shape-(2,3,4) array: +NumPy提供函数[broadcast_to](https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_to.html#numpy.broadcast_to)来将数组广播到某个用户提供的形状。这可以用来帮助我们发展对广播的直观理解。让我们将形状为 (3,4) 的数组广播成一个形状为 (2,3,4) 的数组: ```python -# Demonstrating `np.broadcast_to` +# 演示 `np.broadcast_to` >>> x = np.array([[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]]) -# Explicitly broadcast a shape-(3,4) array -# to a shape-(2,3,4) array. +# 显式将形状为 (3,4) 的数组广播成 +# 形状为 (2,3,4) 的数组 >>> np.broadcast_to(x, (2, 3, 4)) array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], @@ -206,30 +203,30 @@ array([[[ 0, 1, 2, 3],
-**Reading Comprehension: Broadcast Compatibility** +**阅读理解:广播兼容性** -Given the following pairs of array-shapes, determine what the resulting broadcasted shapes will be. Indicate if a pair is broadcast-incompatible. +设以下数组形状对,判断广播后得到的形状是什么并标注形状广播不兼容的对。 -1\. `7 x 2` with `7` +1\. `7 x 2` 和 `7` -2\. `4` with `3 x 4` +2\. `4` 和 `3 x 4` -3\. `1 x 3 x 1` with `8 x 1 x 1` +3\. `1 x 3 x 1` 和 `8 x 1 x 1` -4\. `9 x 2 x 5` with `2 x 5` +4\. `9 x 2 x 5` 和 `2 x 5` -5\. `3` with `3 x 3 x 2` +5\. `3` 和 `3 x 3 x 2`
-## A Simple Application of Array Broadcasting -Here we provide a simple real-world example where broadcasting is useful. Suppose you have a grade book for 6 students, each of whom have taken 3 exams; naturally, you store these scores in a shape-(6,3) array: +## 数组广播的简单应用 +我们在此提供一个简单的使用广播的现实世界范例。假设你有着6个学生的成绩簿,每个成绩簿有着3个考试的成绩,你将这些成绩储存在一个形状为 (6,3) 的数组中: ```python -# grades for 6 students who have taken 3 exams -# axis-0 (rows): student -# axis-1 (columns): exams +# 6个学生3次考试的成绩 +# 轴0(行):学生 +# 轴1(列):考试 >>> import numpy as np >>> grades = np.array([[ 0.79, 0.84, 0.84], ... [ 0.87, 0.93, 0.78], @@ -239,36 +236,33 @@ Here we provide a simple real-world example where broadcasting is useful. Suppos ... [ 0.83, 0.71, 0.85]]) ``` -We might be interested to see how each of these scores compare to the mean score for that specific exam. Based on our discussion from the last section, we can easily compute the mean-score for each exam (rounded to 2 decimal places): +我们可能会想要知道每个成绩和该考试的平均成绩是如何对比的。根据上一节的讨论,我们可以轻松地计算每个考试的平均成绩(四舍五入到小数点后两位): ```python -# compute the mean score for each exam (rounded to 2 decimal places) +# 计算每个考试的平均值(四舍五入到小数点后两位) >>> mean_exam_scores = grades.mean(axis=0) >>> mean_exam_scores = np.round(mean_exam_scores, 2) >>> mean_exam_scores array([ 0.79, 0.85, 0.82]) ``` -`grades` is a shape-(6,3) array and `mean_exam_scores` is a shape-(3,) array, and we want to compute the offset of each exam score from its respective mean. At first glance, it seems like we will have to loop over each row of our `grades` array and subtract from it the `mean_exam_scores`, to compute the offset of each exam score from the respective mean-score: +`grades` 是一个形状为 (6,3) 的数组,而 `mean_exam_scores` 是一个形状为 (3,) 的数组,而我们想要计算每个考试成绩和对应平均值的差。我们的第一反应可能是迭代 `grades` 的每一行并减去对应的 `mean_exam_scores` 来计算差: ```python -# Using a for-loop to compute score offsets. +# 使用for循环来计算成绩差。 -# Shape-(6,3) array that will store (score - mean) for each -# exam score. +# 形状 (6,3) 的数组,用来储存每个考试的(成绩-平均值) score_offset = np.zeros_like(grades) -# iterates over each row of `grades` +# 迭代 `grades` 的每一行 for n, scores_per_student in enumerate(grades): - # `scores_per_student` is a shape-(3,) array of exam scores - # for a given student. This matches the shape of - # `mean_exam_scores`, thus we can perform this subtraction + # `scores_per_student` 是一个形状为 (3,) 的单个学生的考试成绩数组 + # 这和 `mean_exam_scores` 相同,所以我们可以进行减法 score_offset[n] = scores_per_student - mean_exam_scores ``` -Given our discussion of vectorized operations from the last section, you should recoil at the sight of a for-loop in code that is performing array-arithmetic. We might as well get out our abacuses and spreadsheets at this point. Fortunately, we can make use of broadcasting to compute these offsets in a concise, vectorized way: +根据我们上一节对矢量化操作的讨论,你应该立刻因为进行数组算数代码中的for循环而感到作呕。都这样了干嘛不把我们的算盘和表格纸页拿出来。幸运的事,我们可以使用广播来简单,矢量化地计算这些差: ```python -# Using broadcasting to subtract a shape-(3,) array -# from a shape-(6,3) array. +# 使用广播来计算形状为 (6,3) 的数组和形状为 (3,) 的数组的差。 >>> score_offset = grades - mean_exam_scores >>> score_offset array([[ 0. , -0.01, 0.02], @@ -280,30 +274,29 @@ array([[ 0. , -0.01, 0.02], ``` -According to the broadcasting rules detailed above, when you invoke `grades - mean_exam_scores`, NumPy will recognize that `mean_exam_scores` has the same shape as each row of `grades` and thus it will apply the subtraction operation on *each* row of `grades` with `mean_exam_scores`. In effect, the content of `mean_exam_scores` has been *broadcasted* to fill a shape-(6,3) array, so that the element-wise subtraction can be performed. Again, we emphasize that NumPy doesn't actually unnecessarily replicate the data of `mean_exam_scores`, and that this model of broadcasting merely conveys the mathematical process that is transpiring. +根据以上的广播规则,当你调用 `grades - mean_exam_scores` 时,NumPy会发现 `mean_exam_scores` 和 `grades` 的每一行有着相同的形状,因此它会 `grades` 的*每*一行减去 `mean_exam_scores`。也就是说,`mean_exam_scores` 的内容被*广播*来填满一个形状为 (6,3) 的数组,使得对应成员的减法可以进行。我们再次强调,NumPy并不会真的不必要的复制 `mean_exam_scores` 的数据,且我们理解广播的模型仅仅是为了表达这过程中进行的数学运算。
-**Reading Comprehension: Basic Broadcasting** +**阅读理解:基础广播** -Generate a random array of 10,000 2D points using `np.random.rand`. Compute the "center of mass" of these points, which is simply the average x-coordinate and the average y-coordinate of these 10,000 points. Then, use broadcasting to compute the shape-(10000,2) array that stores the position of the points *relative* to the center of mass. For example, if the center of mass is $(0.5, 1)$, and the absolute position of a point is $(2, 3)$, then the position of that point *relative* to the center of mass is simply $(2, 3) - (0.5, 1) = (1.5, 2)$ +使用 `np.random.rand` 生成一个成员为10,000个2维点的随机数组。计算这些点的“质量中心”(center of mass),也就是这10,000个点的平均x坐标和平均y坐标。然后,使用广播来计算储存这些点*相对于*质量中心的坐标的形状为 (10000,2) 的数组。比如说,如果质量中心是 $(0.5, 1)$,一个点的绝对坐标为 $(2, 3)$,那么那个点*相对于*质量中心的位置就是 $(2, 3) - (0.5, 1) = (1.5, 2)$
-## Size-1 Axes & The `newaxis` Object +## 大小为1的轴和 `newaxis` 对象 -### Inserting Size-1 Dimensions into An Array -As conveyed by the broadcasting rules, dimensions of size-1 are special in that they can be broadcasted to any size. Here we will learn about introducing size-1 dimensions into an array, for the purpose of tailoring its shape for broadcasting. +### 向数组插入大小为1的维度 +广播规则也有提到,大小为1的维度因为可以广播成任何大小是特殊的。我们将在这里学习如何向数组中插入大小为1的维度来满足广播的需求。 -You can introduce size-1 dimensions to an array without changing the overall size (i.e. total number of entries in an array. Thus we are free to add size-1 dimensions to an array via the `reshape` function. Let's reshape a shape-(3,) array into a shape-(1, 3, 1, 1) array: +你可以在不改变数组总体大小(也就是数组中总共的成员数)的情况下插入大小为1的维度。所以我们可以随意通过 `reshape` 函数添加大小为1的维度。让我们将一个形状为 (3,) 的数组重塑成形状为 (1, 3, 1, 1) 的数组: ```python >>> import numpy as np -# Reshaping an array to introduce size-1 dimensions. -# The size of the array is 3, regardless of introducing -# these extra size-1 dimensions. +# 通过重塑数组来插入大小为1的维度 +# 在插入大小为1的维度前后数组的大小都是3. >>> np.array([1, 2, 3]).reshape(1, 3, 1, 1) array([[[[1]], @@ -312,9 +305,9 @@ array([[[[1]], [[3]]]]) ``` -Thus the 1-D array with three entries has been reshaped to possess 4-dimensions: "one stack of three sheets, each containing a single row and column". There is another way to introduce size-1 dimensions. NumPy provides the `newaxis` object for this purpose. Let's immediately demonstrate how `np.newaxis` can be used: +就像这样,一个有着3个成员的1维数组就被重塑成了4维数组:“一打三页,每页有着一行一列”。我们有另外一种插入大小为1的维度的方法。NumPy为此提供了 `newaxis` 对象。让我们立刻演示一下 `np.newaxis` 可以如何使用: ```python -# demonstrating the usage of the `numpy.newaxis` object +# 演示 `numpy.newaxis` 对象得使用方法 >>> x= np.array([1, 2, 3]) >>> y= x[np.newaxis, :, np.newaxis, np.newaxis] >>> y @@ -327,20 +320,19 @@ array([[[[1]], (1, 3, 1, 1) ``` -Indexing `x` as `x[np.newaxis, :, np.newaxis, np.newaxis]` returns a "view" of `x` as a 4D array with size-1 dimensions inserted as axes 0, 2, and 3. The resulting array is not a copy of `x`; it points to the exact same data as `x`, but merely with a different indexing layout. This is no different than what we achieved via reshaping: `x.reshape(1, 3, 1, 1)`. +将 `x` 索引为 `x[np.newaxis, :, np.newaxis, np.newaxis]` 会返回一个 `x` 作为在轴0,2,和3中插入了大小为1的维度4维数组的视阈。得到的数组不是 `x` 的复制品;它指向和 `x` 一样的内置数据,但它仅仅提供了一个不一样的索引框架。这和我们通过是重塑形状得到的结果没有任何区别:`x.reshape(1, 3, 1, 1)`。 -### Utilizing Size-1 Dimensions for Broadcasting -Moving on to a more pressing matter: why would we ever want to introduce these spurious dimensions into an array? Let's take an example to demonstrate the utility of size-1 dimensions. +### 使用大小为1的维度来进行广播 +是时候回答一个更重要的问题了:我们在什么情况下会想要向数组中插入这些看起来没什么用的维度呢?让我们通过一个例子来了解大小为1的维度的作用。 -Suppose that we want to multiply all possible pairs of entries between two arrays: `array([1, 2, 3])` with `array([4, 5, 6, 7])`. That is, we want to perform twelve multiplications, and have access to each result. At first glance, combining a shape-(3,) array with a shape-(4,) array seems inadmissible for broadcasting; we seem to be doomed to perform nested for-loops like a bunch of cavemen and cavewomen. Fortunately, we can make clever use of size-1 dimensions so that we can perform this computation in a vectorized way. +假设我们想要将以下两个数组的所有可能的对组合相乘:`array([1, 2, 3])` 和 `array([4, 5, 6, 7])`。也就是说,我们想要进行12次乘法,并能够访问每个结果。第一眼看,形状为 (3,) 的数组和形状为 (4,) 的数组似乎广播不兼容;我们似乎一定要被迫像使一群史前穴居人一样用嵌套的for循环。幸运的是,我们可以通过聪明地使用大小为1的维度来矢量化地进行这个计算。 -Let's introduce size-1 dimensions into `x`: +让我们向 `x` 插入大小为1的维度: ```python -# Inserting size-1 dimensions into `x` and `y` in -# preparation of broadcasting. +# 向 `x` 和 `y` 插入大小为1的维度来准备广播 >>> x_1d = np.array([1, 2, 3]) >>> x = x_1d.reshape(3, 1) >>> x @@ -351,10 +343,10 @@ array([[1], >>> y = np.array([4, 5, 6, 7]) ``` -`x` is now a shape-(3, 1) array and `y` is a shape-(4,) array. According to the broadcasting rules, these arrays are broadcast-compatible and will multiply to produce a shape-(3, 4) array. Let's see that multiplying these two arrays will exactly produce the twelve numbers that we are after: +`x` 现在是一个形状为 (3, 1) 的数组,而 `y` 是一个形状为 (4,) 的数组。根据广播的规则,这两个数组现在广播兼容,并将乘出一个形状为 (3, 4) 的数组。让我们看看将这两个数组相乘是如何会返回我们想要的刚好12个数字的: ```python -# broadcast-multiplying `x` and `y` +# 广播相乘 `x` 和 `y` >>> x * y array([[ 4, 5, 6, 7], [ 8, 10, 12, 14], @@ -395,16 +387,16 @@ array([[ 4, 5, 6, 7], \end{equation} -See that entry `(i, j)` of the resulting array corresponds to `x_1d[i] * y[j]`. +请注意,返回数组的成员 `(i, j)` 对应着 `x_1d[i] * y[j]`。 -Through the use of simple reshaping, shrewdly inserting size-1 dimensions allowed us to coerce NumPy into performing exactly the combination-multiplication that we desired. Furthermore, a keen understanding of what broadcasting is provides us with a clear interpretation of the structure of the result of this calculation. That is, if I reshape `x` to be a shape-$(M, 1)$ array, and `y` is a shape-$(N,)$ array, then (according to broadcasting rules) `x * y` would produce a shape-$(M, N)$ array storing the product of each of `x`'s $M$ numbers with each of `y`'s $N$ numbers. +通过简单的重塑来精明地插入大小为1的维度使得我们可以逼迫NumPy来进行我们想要的组合乘法。同时,我们对广播的准确理解让我们可以对广播运算的结果形状有着清晰的解释。也就是说,如果我将 `x` 重塑为形状是 $(M, 1)$ 的数组,`y` 的形状为 $(N,)$,那么(根据广播的规则)`x * y` 将会返回一个形状是 $(M, N)$ 的数组,其储存着每个 `x` $M$ 个成员之一和每个 `y` $N$ 个成员之一的乘积。
-**Reading Comprehension: Basic Broadcasting II** +**R阅读理解:基础广播II** -Given the shape-(2,3,4) array: +设以下形状为 (2,3,4) 的数组: ```python >>> x = np.array([[[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], @@ -415,7 +407,7 @@ Given the shape-(2,3,4) array: ... [20, 21, 22, 23]]]) ``` -Normalize `x` such that *each of its rows, within each sheet, will sum to a value of 1*. Make use of the sequential function `np.sum`, which should be called only once, and broadcast-division. +标准化 `x`,使其*每页中每行的数据的和都是1*。使用序列函数 `np.sum`,但你只需要调用它一次,并使用广播除法。
@@ -423,50 +415,50 @@ Normalize `x` such that *each of its rows, within each sheet, will sum to a valu
-**Reading Comprehension: Basic Broadcasting III** +**阅读理解:基础广播III** -A digital image is simply an array of numbers, which instructs a grid of pixels on a monitor to shine light of specific colors, according to the numerical values in that array. +一张电子图片其实就是一个数字数组,其指示显示器的像素根据数组的值去发射具体颜色的光。 -An RGB-image can thus be stored as a 3D NumPy array of shape-$(V, H, 3)$. $V$ is the number of pixels along the vertical direction, $H$ is the number of pixels along the horizontal, and the size-3 dimension stores the red, blue, and green color values for a given pixel. Thus a $(32, 32, 3)$ array would be a 32x32 RBG image. +因此,一张RGB图片可以作为一个3维NumPy数组储存,其形状为 $(V, H, 3)$。$V$ 是竖向的像素数量,$H$ 是横向的像素数量,大小为3的维度储存了像素的红,蓝,绿颜色。因此,一个 $(32, 32, 3)$ 的数组将会是一张32x32的RGB图片。 -You often work with a collection of images. Suppose we want to store N images in a single array; thus we now consider a 4D shape-(N, V, H, 3) array. For the sake of convenience, let's simply generate a 4D-array of random numbers as a placeholder for real image data. We will generate 500, 48x48 RGB images: +我们经常会需要处理图片集。假设我们想要将N张图片储存为一个数组,那么我们可以将其当作一个形状为 $(N, V, H, 3)$ 的4维数组。方便起见,让我们先产生成员为随机数字的4维数组来代替真实的图片数据。我们将会生成500张48x48的RGB图片: ```python >>> images = np.random.rand(500, 48, 48, 3) ``` -Using the sequential function `np.max` and broadcasting, normalize `images` such that the largest value within *each color-channel of each image* is 1. +使用序列函数 `np.max` 和广播,标准化 `images`,使其*每张图片的每个颜色频道*的最大值是1。
-## An Advanced Application of Broadcasting: Pairwise Distances -We will conclude this section by demonstrating an important, non-trivial example of array broadcasting. Here, we will find that the most straightforward use of broadcasting is *not* necessarily the right solution for our problem, and we will see that it can be important to first refactor the mathematical approach taken to perform a calculation before using broadcasting. Specifically, we will see that our initial approach for using of broadcasting is memory-inefficient. +## 广播的高级运用:距离对 +我们将通过演示一个重要,相对复杂的数组广播例子来结束本节。在这个例子中,我们会发现最直接的广播方法*不*一定是我们问题的正确解决方法;我们也会注意到在广播之前首先重构数学公式的重要性。具体来讲,我们会注意到我们最初方法的内存使用效率低的问题。 -Suppose we have two, 2D arrays. `x` has a shape of $(M, D)$ and `y` has a shape of $(N, D)$. We want to compute the Euclidean distance (a.k.a. the $L_2$-distance) between *each pair* of rows between the two arrays. That is, if a given row of `x` is represented by $D$ numbers $(x_0, x_1, \ldots, x_{D-1})$, and similarly, a row `y` is represented by $(y_0, y_1, \ldots, y_{D-1})$, and we want to compute the Euclidean distance between the two rows: +假设我们有着两个2维数组。`x` 的形状为 $(M, D)$,而 `y` 的形状为 $(N, D)$。我们想要计算两个数组之间*每一对*行的欧氏距离(Euclidean distance,也叫 $L_2$-distance)。也就是说,如果 `x` 的任何一行数据为 $D$ 个数字 $(x_0, x_1, \ldots, x_{D-1})$,而 `y` 的一行数据为 $(y_0, y_1, \ldots, y_{D-1})$,且我们想要计算这两行之间的欧氏距离: \begin{equation} \sqrt{(x_{0} - y_{0})^2 + (x_{1} - y_{1})^2 + \ldots + (x_{D-1} - y_{D-1})^2} = \sqrt{\sum_{i=0}^{D-1}{(x_{i} - y_{i})^2}} \end{equation} -Doing this for each pair of rows should produce a total of $M\times N$ distances. The previous subsection stepped us through a very similar calculation, albeit with lower-dimensional arrays. Let's proceed by performing this computation in three different ways: +为每一对行组合进行这个计算将会总共产生 $M\times N$ 个距离。之前一小节演示了一个很相似,但低一维度的计算。让我们通过以下三种方法进行这个计算吧: -1. Using explicit for-loops -2. Using straight-forward broadcasting -3. Refactoring the problem and then using broadcasting +1. 使用显式for循环 +2. 直接地使用广播 +3. 首先重构问题然后再使用广播 -For the sake of being concrete, we will compute all of the pairwise Euclidean distances between the rows of these two arrays: +为了让例子更加实际,我们将会计算以下两个数组之间所有行对的欧氏距离: ```python -# a shape-(5, 3) array +# 形状为 (5, 3) 的数组 >>> x = np.array([[ 8.54, 1.54, 8.12], ... [ 3.13, 8.76, 5.29], ... [ 7.73, 6.71, 1.31], ... [ 6.44, 9.64, 8.44], ... [ 7.27, 8.42, 5.27]]) -# a shape-(6, 3) array +# 形状为 (6, 3) 的数组 >>> y = np.array([[ 8.65, 0.27, 4.67], ... [ 7.73, 7.26, 1.95], ... [ 1.27, 7.27, 3.59], @@ -476,161 +468,151 @@ For the sake of being concrete, we will compute all of the pairwise Euclidean di ``` -Thus we will want to compute a total of 30 distances, one for each pair of rows from `x` and `y`. +因此我们会为 `x` 和 `y` 的每一对行计算总共30个距离。 -### Pairwise Distances Using For-Loops -Performing this computation using for-loops proceeds as follows: +### 使用for循环计算距离对 +使用for循环来计算距离如下: ```python def pairwise_dists_looped(x, y): - """ Computing pairwise distances using for-loops - - Parameters - ---------- - x : numpy.ndarray, shape=(M, D) - y : numpy.ndarray, shape=(N, D) - - Returns - ------- - numpy.ndarray, shape=(M, N) - The Euclidean distance between each pair of - rows between `x` and `y`.""" - # `dists[i, j]` will store the Euclidean - # distance between `x[i]` and `y[j]` + """ 使用for循环计算距离对 + + Parameters + ---------- + x : numpy.ndarray, shape=(M, D) + y : numpy.ndarray, shape=(N, D) + + Returns + ------- + numpy.ndarray, shape=(M, N) + `x` 和 `y` 每一行对的欧氏距离。""" + # `dists[i, j]` 将会存储 `x[i]` and `y[j]` + # 的欧氏距离 dists = np.empty((5, 6)) - for i, row_x in enumerate(x): # loops over rows of `x` - for j, row_y in enumerate(y): # loops over rows of `y` - # Subtract corresponding entries of the rows, - # squares each difference, and then sums them. This - # exactly matches our equation for Euclidean - # distance (we will do the square root later) + for i, row_x in enumerate(x): # 循环遍历 `x` 的行 + for j, row_y in enumerate(y): # 循环遍历 `y` 的行 + # 将两行相对应的成员相减,求每个差的平方,然后求平方差的和。 + # 这和之前给出的欧氏距离公式完全一样(我们会在之后再求 + # 平方根) dists[i, j] = np.sum((row_x - row_y)**2) - # we still need to take the square root of - # each of our numbers + # 我们还需要求所有数字的平方根 return np.sqrt(dists) ``` -Be sure to step through this code and see that `dists` stores each pair of Euclidean distances between the rows of `x` and `y`. +请一步一步理解此代码,并注意到 `dists` 存储 `x` 和 `y` 每一对行的欧氏距离这一事实。 -### Pairwise Distances Using Broadcasting (Unoptimized) -Now, let's use of vectorization to perform this distance computation. It must be established immediately that the method that we about to develop here is memory-inefficient. We will address this issue in detail at the end of this subsection. +### 使用广播计算距离对(未优化) +现在,让我们使用矢量化来进行这个距离计算。首先,请注意,我们将要使用的方法对内存的运用是不高效的。我们将会在本小节结尾仔细地处理此问题。 -We start off our vectorized computation by shrewdly inserting size-1 dimensions into `x` and `y`, so that we can perform $M \times N$ subtractions between their pairs of length-$D$ rows. *This creates a shape-*$(M, N, D)$ *array*. +我们首先将向 `x` 和 `y` 精明的地方插入大小为1的维度来让我们可以对它们长度为 $D$ 的行对进行 $M \times N$ 个减法。*这将创建一个形状为* $(M, N, D)$ *的数组*。 ```python -# subtract shape-(5, 1, 3) with shape-(1, 6, 3) -# produces shape-(5, 6, 3) +# 将形状为 (5, 1, 3) 的数组和形状为 (1, 6, 3) 的数组相减 +# 来产生形状为 (5, 6, 3) 的数组 >>> diffs = x.reshape(5, 1, 3) - y.reshape(1, 6, 3) >>> diffs.shape (5, 6, 3) ``` -It is important to see, via broadcasting, that `diffs[i, j]` stores `x[i] - y[j]`. Thus we need to square each entry of `diffs`, sum over its last axis, and take the square root, in order to produce our $M \times N$ Euclidean distances: +请注意,通过广播,`diffs[i, j]` 现在储存着 `x[i] - y[j]`。因此我们需要将 `diffs` 的每个成员平方,求每行列在最后一轴的和,并最后平方根所有数字来返回 $M \times N$ 个欧氏距离: ```python -# producing the Euclidean distances +# 创建欧氏距离 >>> dists = np.sqrt(np.sum(diffs**2, axis=2)) >>> dists.shape (5, 6) ``` -Voilà! We have produced the distances in a vectorized way. Let's write this out formally as a function: +就这么简单!我们通过矢量化方法创建了这些距离。现在,让我们将其正式编为一个函数: ```python def pairwise_dists_crude(x, y): - """ Computing pairwise distances using vectorization. - - This method uses memory-inefficient broadcasting. - - Parameters - ---------- - x : numpy.ndarray, shape=(M, D) - y : numpy.ndarray, shape=(N, D) - - Returns - ------- - numpy.ndarray, shape=(M, N) - The Euclidean distance between each pair of - rows between `x` and `y`.""" - # The use of `np.newaxis` here is equivalent to our - # use of the `reshape` function + """ 使用矢量化计算距离对 + + Parameters + ---------- + x : numpy.ndarray, shape=(M, D) + y : numpy.ndarray, shape=(N, D) + + Returns + ------- + numpy.ndarray, shape=(M, N) + `x` 和 `y` 每一行对的欧氏距离。""" + # 在这里使用的 `np.newaxis` 达到和我们之前运用 `reshape` + # 函数一样的结果 return np.sqrt(np.sum((x[:, np.newaxis] - y[np.newaxis])**2, axis=2)) ``` -Regrettably, there is a glaring issue with the vectorized computation that we just performed. Consider the largest sized array that is created in the for-loop computation, compared to that of this vectorized computation. The for-loop version need only create a shape-$(M, N)$ array, whereas the vectorized computation creates an intermediate array (i.e. `diffs`) of shape-$(M, N, D)$. This intermediate array is even created in the one-line version of the code. This will create a massive array if $D$ is a large number! +可惜的是,我们这里进行的矢量化计算有一个明显的问题。请对比在for循环版本中创建的大小最大的数组和在这个矢量化计算中创建的最大数组。for循环版本仅仅需要创建一个形状为 $(M, N)$ 的数组,而矢量化版本会创建一个形状为 $(M, N, D)$ 的过渡数组(也就是 `diffs`)。这个过渡数组甚至会在函数中的一行代码中被创建。当 $D$ 是一个大数时这个过渡数组会非常大! -Suppose, for instance, that you are finding the Euclidean between pairs of RGB images that each have a resolution of $32 \times 32$ (in order to see if the images resemble one another). Thus in this scenario, each image is comprised of $D = 32 \times 32 \times 3 = 3072$ numbers ($32^2$ pixels, and each pixel has 3 values: a red, blue, and green-color value). Computing all the distances between a stack of 5000 images with a stack of 100 images would form an intermediate array of shape-$(5000, 100, 3072)$. Even though this large array only exists temporarily, it would have to consume over 6GB of RAM! The for-loop version requires $\frac{1}{3027}$ as much memory (about 2MB). +比如说,假设你在试图计算分辨率为 $32 \times 32$ 的RGB图片之间的欧氏距离(来计算图片是否相似)。那么在这个情况下,每张图片被 $D = 32 \times 32 \times 3 = 3072$($32^2$ 个像素,且每个像素有3个值:红,绿,蓝)个数字描述。那么计算一打5000张图片和一打100张图片之间的所有距离对会创建一个形状为 $(5000, 100, 3072)$ 的过渡数组。虽然这个大数组只会暂时存在,但是它会需要超过6GB的内存!for循环版本只需要 $\frac{1}{3027}$ 多的内存(大约2MB)。 -Is our goose cooked? Are we doomed to pick between either slow for-loops, or a memory-inefficient use of vectorization? No! We can refactor the mathematical form of the Euclidean distance in order to avoid the creation of that bloated intermediate array. +是否已经木已成舟了?我们是否必须要在缓慢的for循环和内存使用效率低的矢量化中做选择呢?不!小孩子才做选择题,成年人当然是全都要!我们可以重构欧氏距离的数学公式来避免创建巨大的过渡数组。 -### Optimized Pairwise Distances -Performing the pairwise subtraction between the respective rows of `x` and `y` is what created the over-sized intermediate array in our previous calculation. Thus we want to rewrite the Euclidean distance equation such that none of the terms require broadcasting beyond the size of $M \times N$. +### 优化过的距离对 +在之前的计算中,对 `x` 和 `y` 的对应行进行减法是创建过大过渡数组的罪魁祸首。因此,我们想要重写欧氏距离公式来使得没有任何项需要广播到大于 $M \times N$ 的数组。 -The Euclidean distance equation, ignoring the square root for now, can be refactored by multiplying out each squared term as so: +暂时抛开平方根,欧氏距离公式的每一项平方差可以被重构为如下: \begin{equation} \sum_{i=0}^{D-1}{(x_{i} - y_{i})^2} = \sum_{i=0}^{D-1}{x_{i}^2} + \sum_{i=0}^{D-1}{y_{i}^2} - 2\sum_{i=0}^{D-1}{x_{i} y_{i}} \end{equation} -Keep in mind that we must compute this for each pair of rows in `x` and `y`. We will find that this formulation permits the use of matrix multiplication, such that we can avoid forming the shape-$(M, N, D)$ intermediate array. +请注意,我们必须为 `x` 和 `y` 的每一对行计算这个差。我们将会发现这个版本的公式允许我们使用矩阵乘法来避免创建形状为 $(M, N, D)$ 的过渡数组。 -The first two terms in this equation are straight-forward to calculate, and, when combined, will only produce a shape-$(M, N)$ array. For both `x` and `y`, we square each element in the array and then sum over the columns for each row: +这个公式的前两项可以很直接地去计算并相加,而仅仅会创建形状为 $(M, N)$ 的数组。我们平方 `x` 和 `y` 的每一项并在每一行求和: ```python -# Computing the first two terms of the -# refactored Euclidean distance equation +# 计算重构后的欧氏距离公式的前两项 -# creates a shape-(5,) array +# 创建一个形状为 (5,) 的数组 >>> x_sqrd_summed = np.sum(x**2, axis=1) -# creates a shape-(6,) array +# 创建一个形状为 (6,) 的数组 >>> y_sqrd_summed = np.sum(y**2, axis=1) ``` -We must insert a size-1 dimension in `x` so that we can add all pairs of numbers between the resulting shape-$(M, 1)$ and shape-$(N,)$ arrays. This will compute $\sum_{i=0}^{D-1}{x_{i}^2} + \sum_{i=0}^{D-1}{y_{i}^2}$ for all of the $M \times N$ pairs of rows: +我们需要向 `x` 插入一个大小为1的维度来让我们将相加形状为 $(M, 1)$ 和 $(N,)$ 数组的每一对数。这将为所有 $M \times N$ 个行对计算 $\sum_{i=0}^{D-1}{x_{i}^2} + \sum_{i=0}^{D-1}{y_{i}^2}$。 ```python -# add a shape-(5, 1) array with a shape-(6, ) array -# to create a shape-(5, 6) array +# 将形状为 (5, 1) 和 (6, ) 的数组相加来创建形状为 (5, 6) 的数组 >>> x_y_sqrd = x_sqrd_summed[:, np.newaxis] + y_sqrd_summed >>> x_y_sqrd.shape (5, 6) ``` -This leaves the third term to be computed. It is left to the reader to show that computing this sum of products for each pair of rows in `x` and `y` is equivalent to performing the matrix multiplication $-2\;(x \cdot y^{T})$, where `y` has been transposed so that it has a shape of $(D, N)$. This matrix multiplication of a shape-$(M, D)$ array with a shape-$(D, N)$ array produces a shape-$(M, N)$ array. Therefore, we can compute this final term without needing to create a larger, intermediate array. +现在,我们只剩下第三项需要计算。我们留给读者来证明计算 `x` 和 `y` 每一行对的乘积的和等值于矩阵乘法 $-2\;(x \cdot y^{T})$,其中 `y` 被转制为形状 $(D, N)$。形状为 $(M, D)$ 的数组和形状为 $(D, N)$ 的数组的矩阵乘法将创建一个形状为 $(M, N)$ 的数组。因此,我们可以在不创建更大的过渡数组的情况下计算这最后一项。 -Thus the third term in our equation, $-2\sum_{i=0}^{D-1}{x_{i} y_{i}}$, for all $M \times N$ pairs of rows, is: +因此,我们所有 $M \times N$ 个行对的公式第三项 $-2\sum_{i=0}^{D-1}{x_{i} y_{i}}$ 为: ```python -# computing the third term in the distance -# equation, for all pairs of rows ->>> x_y_prod = -2 * np.matmul(x, y.T) # `np.dot` can also be used to the same effect +# 计算所有行对的距离公式第三项 +>>> x_y_prod = -2 * np.matmul(x, y.T) # 你也可以使用 `np.dot` 来达成一样的效果 >>> x_y_prod.shape (5, 6) ``` -Having accounted for all three terms, we can finally compute the Euclidean distances: +在计算完全部三项后,我们终于可以计算欧氏距离了: ```python -# computing all the distances +# 计算所有距离 >>> dists = np.sqrt(x_y_sqrd + x_y_prod) >>> dists.shape (5, 6) ``` -In total, we have successfully used vectorization to compute the all pairs of distances, while only requiring an array of shape-$(M, N)$ to do so! This is the memory-efficient, vectorized form - the stuff that dreams are made of. Let's write the function that performs this computation in full. +总结一下,我们成功地使用了矢量化方法来计算所有距离对,而过程中仅仅使用了形状为 $(M, N)$ 的数组!这方法既高效地使用了内存,又是矢量化版本——理想世界不过如此。让我们编写完整进行以上计算的函数。 ```python def pairwise_dists(x, y): - """ Computing pairwise distances using memory-efficient - vectorization. + """ 使用省内存的矢量化方法计算距离对。 Parameters ---------- @@ -640,8 +622,7 @@ def pairwise_dists(x, y): Returns ------- numpy.ndarray, shape=(M, N) - The Euclidean distance between each pair of - rows between `x` and `y`.""" + `x` 和 `y` 每一行对的欧氏距离。""" dists = -2 * np.matmul(x, y.T) dists += np.sum(x**2, axis=1)[:, np.newaxis] dists += np.sum(y**2, axis=1) @@ -653,69 +634,70 @@ def pairwise_dists(x, y):
-**Takeaway**: +**经验**: -The specific form of an equation can have a major impact on the memory-footprint of its vectorized implementation in NumPy. This issue can be safely overlooked in cases where you can be certain that the array shapes at play will not lead to substantial memory consumption. Otherwise, take care to study the form of the equation, to see if it can be recast in a way that alleviates its memory-consumption bottlenecks. +公式的具体格式可能会对NumPy矢量化的实现的内存使用量有着巨大的影响。在你可以确定数组形状不会导致明显的内存使用时可以安全地无视这个问题。但如果你不能确定,那么花些时间思考一下公式的格式来看看你是否能够重写它来减缓内存使用的瓶颈。
-**Reading Comprehension: Checking the equivalence of the three pairwise distance functions** +**阅读理解:检查三个距离对公式是否等值** -Use the function [numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html) to verify that the three methods for computing the pairwise distances produce the same numerical results. +使用函数[numpy.allclose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)来检查以上三种计算距离对的公式返回的结果是一样的。
-## Links to Official Documentation +## 官方说明文档链接 + +- [广播基础](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#broadcasting) +- [广播常规](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#changing-number-of-dimensions) + -- [Basics of broadcasting](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html#broadcasting) -- [Broadcasting routines](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#changing-number-of-dimensions) +## 阅读理解答案 +**广播兼容性:解** -## Reading Comprehension Solutions +1\. 不兼容 + +2\. `3 x 4` + +3\. `8 x 3 x 1` + +4\. `9 x 2 x 5` + +5\. 不兼容 -**Basic Broadcasting: Solution** +**基础广播:解** -Generating the random array of 10,000, 2D points, and their "center-of-mass". +生成成员为10,000个2维点的数组并计算它们的“质量中心”。 ```python -# find the mean x-coord and y-coord of the 10000 points +# 计算10000个点的平均x和y坐标 >>> pts = np.random.rand(10000, 2) >>> center_of_mass = pts.mean(axis=0) # -> array([mean_x, mean_y]) >>> center_of_mass.shape (2,) -# Use broadcasting to compute the position of each point relative -# to the center of mass. The center of mass coordinates are subtracted -# from each of the 10000 points, via broadcast-subtraction +# 使用广播来计算每个点相对质量中心的坐标。通过广播减法来为所有10000个点 +# 减去质量中心的坐标 >>> relative_pos = pts - center_of_mass # shape-(10000,2) w/ shape-(2,) >>> relative_pos.shape (10000, 2) ``` -**Broadcast Compatibility: Solution** - -1\. Incompatible - -2\. `3 x 4` - -3\. `8 x 3 x 1` - -4\. `9 x 2 x 5` -5\. Incompatible -**Basic Broadcasting II: Solution** +**基础广播II:解** -Normalize `x` such that *each of its rows, within each sheet, will sum to a value of 1*. Make use of the sequential function `np.sum`, which should be called only once, and broadcast-division. +标准化 `x`,使其*每页中每行的数据的和都是1*。使用序列函数 `np.sum`,但你只需要调用它一次,并使用广播除法。 ```python -# a shape-(2, 3, 4) array +# 形状为 (2, 3, 4) 的数组 >>> x = np.array([[[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]], @@ -724,19 +706,17 @@ Normalize `x` such that *each of its rows, within each sheet, will sum to a valu ... [16, 17, 18, 19], ... [20, 21, 22, 23]]]) -# sum along each of the three rows within each sheet +# 求每一页三行中的和 >>> summed_rows = x.sum(axis=2) >>> summed_rows array([[ 6, 22, 38], [54, 70, 86]]) -# this shape-(2, 3) array can be broadcast-divided -# along the sheets and rows of `x`, if we insert a size-1 axis -# at dimension-2 of the summed array, where the columns used to -# be +# 这个形状为 (2, 3) 的数组可以广播来于 `x` 的每一页和行相减。 +# 我们只需要在和数组的维度2中插入一个大小为1的轴来代替之前的行就行 >>> x_norm = x / summed_rows[:, :, np.newaxis] -# verifying the solution +# 检查答案 >>> x_norm.sum(axis=2) array([[1., 1., 1.], [1., 1., 1.]]) @@ -744,21 +724,20 @@ array([[1., 1., 1.], -**Basic Broadcasting III: Solution** +**基础广播III:解** ```python -# a collection of 500 48x48 RGB images +# 500张48x48RGB图的集合 >>> images = np.random.rand(500, 48, 48, 3) -# finding the max-value within each color-channel of each image +# 计算每张图每个颜色频道的最大值 >>> max_vals = images.max(axis=(1,2)) >>> max_vals.shape (500, 3) -# we can insert size-1 dimensions so that we can -# broadcast-divide these max-values with -# the pixels of the images. -# broadcasting (500, 48, 48, 3) with (500, 1, 1, 3) +# 我们可以通过插入大小为1的维度来广播相除这些最大值 +# 和图片中的像素。 +# 为相除形状 (500, 48, 48, 3) 将最大值数组广播为形状 (500, 1, 1, 3) >>> normed_images = images / max_vals.reshape(500, 1, 1, 3) # checking that all the max-values are 1 @@ -771,16 +750,16 @@ array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) -# a rigorous check +# 严格的检查 >>> np.all(normed_images.max(axis=(1,2)) == 1) True ``` -**Checking the equivalence of the three pairwise distance functions: Solution** +**检查三个距离对公式是否等值:解** -`numpy.allclose` returns `True` if all pairwise elements between two arrays are almost-equal to one another. +`numpy.allclose` 当两个数组所有对应的成员基本相同时返回 `True`。 ```python >>> x = np.array([[ 8.54, 1.54, 8.12], diff --git a/Python/Module3_IntroducingNumpy/FunctionsForCreatingNumpyArrays.md b/Python/Module3_IntroducingNumpy/FunctionsForCreatingNumpyArrays.md index 67f18ec..34941e0 100644 --- a/Python/Module3_IntroducingNumpy/FunctionsForCreatingNumpyArrays.md +++ b/Python/Module3_IntroducingNumpy/FunctionsForCreatingNumpyArrays.md @@ -4,73 +4,72 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Creating numpy arrays, Difficulty: Easy, Category: Section :keywords: create array, ndarray, ones, random, zeros, empty, examples, arange, linspace, reshape, hstack, vstack -``` + -# Functions for Creating NumPy Arrays -This section presents standard methods for creating NumPy arrays of varying shapes and contents. NumPy provides a laundry list of functions for creating arrays: +# 创建NumPy数组的函数 +本节将会讨论创建不同形状和内容的NumPy数组的方法。NumPy提供了非常多的创建数组的函数: ```python >>> import numpy as np -# creating an array from a Python sequence +# 使用Python序列创建数组 >>> np.array([i**2 for i in range(5)]) array([ 0, 1, 4, 9, 16]) -# creating an array filled with ones +# 创建成员都是1的数组 >>> np.ones((2, 4)) array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) -# creating an array of evenly-spaced points +# 创建成员为均匀分布数字的数组 >>> np.linspace(0, 10, 5) array([ 0. , 2.5, 5. , 7.5, 10. ]) -# creating an array by sampling 10 numbers -# randomly from a mean-1, std-dev-5 normal -# distribution +# 通过随机从平均值为1,标准差为5的正态分布中 +# 抽取10个数字来创建一个数组 >>> np.random.normal(1, 5, 10) array([ 2.549537 , 2.75144951, 0.60031823, 3.75185732, 4.65543858, 0.55779525, 1.15574987, -1.98461337, 5.39771083, -7.81395192]) -# creating an array of a specified datatype +# 创建某个特定数据类型的数组 >>> np.array([1.5, 3.20, 5.78], dtype=int) array([1, 3, 5]) ``` -## Creating Arrays from Python Sequences -You can create an array from a Python `list` or `tuple` by using NumPy's `array` function. NumPy will interpret the structure of the data it receives to determine the dimensionality and shape of the array. For example, a single list of numbers will be used to create a 1-dimensional array: +## 使用Python序列创建数组 +你可以利用NumPy的 `array` 函数利用Python的 `list` 或 `tuple` 来创建数组。NumPy将分析它接受的数据结构来决定数组的维度和形状。比如说,一列表的数字将会被用来创建一个1维数组: ```python -# a list of numbers will become a 1D-array ->>> np.array([1., 2., 3.]) # shape: (3,) +# 一列表的数字会成为1维数组 +>>> np.array([1., 2., 3.]) # 形状:(3,) array([ 1., 2., 3.]) ``` -Nested lists/tuples will be used to construct multidimensional arrays. For example, a "list of equal-length lists of numbers" will lead to a 2-dimensional array; each of the inner-lists comprises a row of the array. Thus a list of two, length-three lists will produce a (2,3)-shaped array: - +嵌套的列表/元组将会被用来创建多维数组。比如说,“成员为等长的数字列表的列表”将会成为2维数组;列表中的每一个子列表都会成为数组中的一行。因此,一个长度为2,成员为长度为3的列表将会导致一个形状为 (2,3) 的数组被创建: + ```python -# a list of lists of numbers will produce a 2D-array ->>> np.array([[1., 2., 3.], [4., 5., 6.]]) # shape: (2, 3) +# 一列表的数字列表将会创建2维数组 +>>> np.array([[1., 2., 3.], [4., 5., 6.]]) # 形状:(2, 3) array([[ 1., 2., 3.], [ 4., 5., 6.]]) ``` -A "list of equal-length lists, of equal-length lists of numbers" creates a 3D-array, and so on. Recall that using repeated concatenation, `[0]*3` will produce `[0, 0, 0]`. Using this, let's create two lists, each containing three lists, each containing four zeros; feeding this to `np.array` thus produces a 2x3x4 array of zeros: +“成员为成员为等长的数字列表的等长数字列表的列表”将会成为3维数组,如此反复。请回忆,通过使用重复粘贴,`[0]*3` 将会创建 `[0, 0, 0]`。让我们使用这个来创建两个成员为三个每个包含四个0的列表的列表吧;因此将这个列表输入到 `np.array` 中会创建一个2x3x4的内容为0的数组: ```python -# A list of lists of lists of zeros creates a 3D-array +# 一列表的数字0列表的列表会成为一个3维数组 >>> np.array([[[0]*4]*3]*2) array([[[0, 0, 0, 0], [0, 0, 0, 0], @@ -81,109 +80,108 @@ array([[[0, 0, 0, 0], [0, 0, 0, 0]]]) ``` -You will seldom use lists to form high-dimensional arrays like this. Instead, there are other array-creation functions that are more amendable to generating high-dimensional data, which we will introduce next. For example, we will see that the `np.zeros` function is a much more civilized way to create a high-dimensional array of zeros. +你很少会需要使用列表来像这样创建高维数组。与其如此,我们将在下面介绍其它更加方便生成高维度数据的数组创建函数。比如说,我们将会看到 `np.zeros` 函数为我们提供了一个更文明的创建高维0数组的方法。
-**Warning!** +**警告**! -You actually *can* create an array from lists of *unequal* lengths. The resulting array is **not** an ND-array as it has no well-defined dimensionality. Instead, something called an *object-array* is produced, which does not benefit from the majority of NumPy's features. This is a relatively obscure feature of the NumPy library, and should be avoided unless you really know what you're doing! +你其实*可以*通过成员为*不等长*列表的列表来创建数组。这样做产生的数组并*不是*一个N维数组,因为它没有定义明确的维度。这样做会产生一个*对象数组*(object array),而它并不能享受大部分的NumPy功能和好处。这是NumPy模组比较少见的一个特征。如果你不真的很清楚自己在做什么的话就避免使用它!
-## Creating Constant Arrays: `zeros` and `ones` -NumPy provides the functions `zeros` and `ones`, which will fill an array of user-specified shape with 0s and 1s, respectively: +## 创建常量数组:`zeros` 和 `ones` +NumPy提供了函数 `zeros` 和 `ones`,其创建用户提供形状的成员数字分别为0和1的数组。 ```python -# create a 3x4 array of zeros +# 创建一个 3x4 的0数组 >>> np.zeros((3, 4)) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) -# create a shape-(4,) array of ones +# 创建一个形状为 (4,) 的1数组 >>> np.ones((4,)) array([ 1., 1., 1., 1.]) ``` -NumPy provides additional functions for creating constant-valued arrays. Please refer to [the official documentation](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#ones-and-zeros) for a complete listing. +NumPy提供了额外的创建常数值数组的函数。请查看[官方说明文档](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#ones-and-zeros)来阅读完整的列表。 -## Creating Sequential Arrays: `arange` and `linspace` -The [arange](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html#numpy.arange) function allows you to initialize a sequence of integers based on a starting point (inclusive), stopping point (exclusive), and step size. This is very similar to the `range` function; however `arange` immediately creates this sequence as an array, whereas `range` produces a generator. +## 创建序列数组:`arange` 和 `linspace` +[arange](https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html#numpy.arange)函数允许你根据一个起始点(start)(包含),结尾点(stop)(不包含),和步距(step)来初始化一序列的整数。这和 `range` 函数很相似;但是,`arange` 将立刻将这个序列创建成数组,而 `range` 返回一个生成器。 ```python ->>> np.arange(0, 10, 1) # start (included): 0, stop (excluded): 10, step:1 +>>> np.arange(0, 10, 1) # start(包含):0,stop(不包含):10,step:1 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) -# supplying one value to `arange` amounts to specifying the stop value -# start=0 and step=1 are then used as defaults ->>> np.arange(10) # equivalent to: start: 0, stop: 10, step:1 +# 仅仅为 `arange` 提供一个数字相当于为其提供结尾点 +# 默认使用start=0 和 step=1 +>>> np.arange(10) # 等值于:start:0,stop:10,step:1 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ->>> np.arange(-5, 6, 2) # start (included): -5, stop (excluded): 6, step:2 +>>> np.arange(-5, 6, 2) # start(包含):-5,stop(不包含):6,step:2 array([-5, -3, -1, 1, 3, 5]) ``` -The [linspace](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html) function allows you to generate $N$ *evenly-spaced* points within a user-specified interval $[i, j]$ ($i$ and $j$ are included in the interval). This is often used to generate a domain of values on which to evaluate a mathematical function (e.g. if you want to the sine function from $-\pi$ to $\pi$ on a finely-divided grid). +[linspace](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html)函数提供了在用户提供的范围 $[i, j]$($i$ 和 $j$ 都在这个范围内包括)内生成 $N$ 个*等距*的点的功能。这函数经常用来生成计算数学函数时使用的输入域值(例,在 $-\pi$ to $\pi$ 之间等距计算sine函数的值)。 ```python -# generate five evenly-spaced points on the interval [-1, 1] +# 在 [-1, 1] 中生成5个等距的点 >>> np.linspace(-1, 1, 5) array([-1. , -0.5, 0. , 0.5, 1. ]) -# generate two evenly-spaced points on the interval [3, 4] +# 在 [3, 4] 中生成2个等距的点 >>> np.linspace(3, 4, 2) array([ 3., 4.]) -# generate 100 evenly-spaced points on the interval [-pi, pi] +# 在 [-pi, pi] 中生成100个等距的点 >>> np.linspace(-np.pi, np.pi, 100) array([-3.14159265, ..., 3.14159265]) ``` -Numpy has other functions for creating sequential arrays, such as producing an array spaced evenly on a log-scaled interval. See the [official documentation](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#numerical-ranges) for a complete listing. +NumPy提供了其它用来创建序列数组的函数,如在对数刻度上创建等距数组。请查看[官方说明文档](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#numerical-ranges)来阅读完整列表。 -## Creating Arrays Using Random Sampling -Several functions can be accessed from `np.random`, which populate arrays of a user-specified shape by drawing randomly from a specified statistical distribution: +## 随机取值来生成数组 +在 `np.random` 中有多个函数可以根据用户的形状创建数组,其值由某用户选择的统计分布中随机抽取得到: ```python -# create a shape-(3,3) array by drawing its entries randomly -# from the uniform distribution [0, 1) +# 通过在 [0, 1) 中均匀分布来创建形状为 (3,3) 的数组 >>> np.random.rand(3,3) array([[ 0.09542611, 0.13183498, 0.39836068], [ 0.7358235 , 0.77640024, 0.74913595], [ 0.37702688, 0.86617624, 0.39846429]]) -# create a shape-(5,) array by drawing its entries randomly -# from a mean-0, variance-1 normal (a.k.a. Gaussian) distribution +# 通过从平均值为0,方差为1的正态分布(也就是高斯分布)中抽取值 +# 来创建形状为 (5,) 的数组 >>> np.random.randn(5) array([-1.11262121, -0.35392007, 0.4245215 , -0.81995588, 0.65412323]) ``` -There are [many more functions](https://docs.scipy.org/doc/numpy/reference/routines.random.html#distributions) to read about that allow you to draw from a wide variety of statistical distributions. This only scratches the surface of random number generation in NumPy. +当然,NumPy有着[非常多其它的函数](https://docs.scipy.org/doc/numpy/reference/routines.random.html#distributions)来允许你从很多种类的统计分布中抽取值。本文介绍的内容仅仅NumPy中随机生成数字功能的皮毛而已。 -## Creating an Array with a Specified Data Type -Each of the preceding functions used to create an array can be passed a so-called 'keyword' argument, `dtype`, which instructs NumPy to use a specified data type when producing the contents of the array. +## 创建某数据类型的数组 +在之前的所有函数中你都可以向其输入一个关键词参数 `dtype` 来指示NumPy在创建函数内容时使用指定的数据类型。 ```python -# populate an array using 32-bit floating point numbers +# 向数组中填满32比特的浮点数 >>> np.array([1, 2, 3], dtype="float32") array([ 1., 2., 3.], dtype=float32) -# default data type produced by `arange` is 32-bit integers +# `arange` 使用的默认数据类型为32比特整数 >>> np.arange(0, 4).dtype dtype('int32') -# the data type produced by `arange` can be specified otherwise +# 通过设置 `dtype` 你可以调整 `arange` 产生的数据类型 >>> np.arange(0, 4, dtype="float16") array([ 0., 1., 2., 3.], dtype=float16) -# generate shape-(4,4) array of 64-bit complex-valued 0s +# 生成形状为 (4,4) 的数组,其成员为64比特的复数0 >>> np.zeros((4, 4), dtype="complex64") array([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], @@ -191,35 +189,35 @@ array([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]], dtype=complex64) ``` -Refer to [the official NumPy documentation](https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types) for the complete list of available array datatypes. +请查看[NumPy官方说明文档](https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types)来阅读完整的可用数组数据类型列表。 -## Joining Arrays Together -Similar to Python lists and tuples, NumPy arrays can be concatenated together. However, because NumPy's arrays can be multi-dimensional, we can choose the dimension along which arrays are joined. +## 合并数组 +和Python的列表和元组类似,1你可以粘连多个NumPy数组。但是,因为NumPy的数组可以是多维度的,我们可以选择粘连数组的维度。 ```python -# demonstrating methods for joining arrays +# 演示合并数组的方法 >>> x = np.array([1, 2, 3]) >>> y = np.array([-1, -2, -3]) -# stack `x` and `y` "vertically" +# 将 `x` 和 `y` “竖向”(vertically)堆积(stack) >>> np.vstack([x, y]) array([[ 1, 2, 3], [-1, -2, -3]]) -# stack `x` and `y` "horizontally" +# 将 `x` 和 `y` “横向”(horizontally)堆积 >>> np.hstack([x, y]) array([ 1, 2, 3, -1, -2, -3]) ``` -A complete listing of functions for joining arrays can be [found in the official NumPy documentation](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#joining-arrays). There are also corresponding functions for splitting an array into independent arrays. +合并数组的完整函数列表[可以在NumPy官方说明文档](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#joining-arrays)找到。NumPy也提供对应的函数来将单个数组切分成多个独立数组。 -## Links to Official Documentation +## 官方说明文档链接 -- [Constant arrays](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#ones-and-zeros) +- [常数数组](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#ones-and-zeros) - [numpy.array](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy-array) -- [Sequential arrays](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#numerical-ranges) -- [Random distributions](https://docs.scipy.org/doc/numpy/reference/routines.random.html#distributions) -- [Array types](https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types) -- [Joining arrays](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#joining-arrays) +- [序列数组](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html#numerical-ranges) +- [随机分布](https://docs.scipy.org/doc/numpy/reference/routines.random.html#distributions) +- [数组类型](https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types) +- [合并数组](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#joining-arrays) diff --git a/Python/Module3_IntroducingNumpy/IntroducingTheNDarray.md b/Python/Module3_IntroducingNumpy/IntroducingTheNDarray.md index a5c0ffa..fec6c89 100644 --- a/Python/Module3_IntroducingNumpy/IntroducingTheNDarray.md +++ b/Python/Module3_IntroducingNumpy/IntroducingTheNDarray.md @@ -4,46 +4,46 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.0-rc0 + format_version: '1.2' + jupytext_version: 1.3.0rc2 kernelspec: display_name: Python 3 language: python name: python3 --- -```raw_mimetype="text/restructuredtext" + .. meta:: :description: Topic: Introduction to numpy arrays, Difficulty: Easy, Category: Section :keywords: numpy array, ndarray, introduction, overview -``` + -# Introducing the ND-array -It is time to start familiarizing ourselves with NumPy, the premiere library for doing numerical work in Python. To use this package, we need to be sure to "import" the NumPy module into our code: +# N维数组简介 +是时候让我们了解NumPy——在Python中做数字工作的旗舰模组——了!以使用此模组,我们需要在代码中“导入”(import)NumPy模组: ```python import numpy as np ``` -You could have run `import numpy` instead, but the prescribed method allows us to use the abbreviation 'np' throughout our code, instead of having to write 'numpy'. This is a very common abbreviation to use. +你也可以运行 `import numpy` 来代替以上语句,但是以上语句允许我们在代码中使用简写 'np' 而不需要写出全称 'numpy'。这是一个常用的简写。 + +N维数组(ND-array)是NumPy模组的明星。它能够存储一序列的数字。像Python列表一样,你可以通过“索引”(indexing)来访问该数组的成员,也可以通过“切片”(slicing)来访问数组的子序列。那么NumPy的N维数组和Python列表有什么区别,且为什么有一整个围绕着这个数组的数字模组呢?N维数组特殊于以下两点。它可以: -The ND-array (N-dimensional array) is the star of the show for NumPy. This array simply stores a sequence of numbers. Like a Python list, you can access individual entries in this array by "indexing" into the array, and you can access a sub-sequence of the array by "slicing" it. So what distinguishes NumPy's ND-array from a Python list, and why is there a whole numerical library that revolves around this array? There are two major features that makes the ND-array special. It can: + 1. 提供在多个维度访问它内在数据的接口。 + 2. 通过编译的C代码(而不是Python代码)高效地对其成员或有规律的子序列进行数学操作;这个过程叫做矢量化(vectorization)。 - 1. Provide an interface for its underlying data to be accessed along multiple dimensions. - 2. Rapidly perform mathematical operations over all of its elements, or over patterned subsequences of its elements, using compiled C code instead of Python; this is a process called vectorization. - -Let's take a sneak peek to see at what this module has in store. The following code creates an ND-array containing the numbers 0-8: +让我们扫一眼这个模组提供的内容吧。以下代码创建了一个内容为数字0-8的N维数组: ```python >>> import numpy as np >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]) ``` -This object is belongs to the NumPy-defined type `numpy.ndarray`. +此对象属于NumPy定义的类 `numpy.ndarray`。 ```python -# An ND-array belongs to the type `numpy.ndarray` +# N维数组属于类 `numpy.ndarray` >>> type(x) numpy.ndarray @@ -53,7 +53,7 @@ True -We can "reshape" this array so that its contents can be accessed along 2 dimensions: +我们可以重塑(reshape)此数组的形状,使其可以在2个维度中被访问: ```python >>> x = x.reshape(3,3) >>> x @@ -62,21 +62,21 @@ array([[0, 1, 2], [6, 7, 8]]) ``` -We will utilize one of NumPy's "vectorized" functions to square each entry in the array (without us needing to write a for-loop) +我们将使用NumPy的一个“矢量化”过的函数来为数组中每一个数都求平方(而不需要编写for循环): ```python ->>> np.power(x, 2) # can also be calculated using the shorthand: x**2 +>>> np.power(x, 2) # 也可以使用简写来计算:x**2 array([[ 0, 1, 4], [ 9, 16, 25], [36, 49, 64]], dtype=int32) ``` -Let's take the mean value over the three distinct columns in our data: +让我们求数据每一列的平均值: ```python >>> np.mean(x, axis=1) array([ 1., 4., 7.]) ``` -We can use broadcasting to raise each column of `x` to a different power: +我们可以使用广播来为 `x` 的每一列求多个不同的幂: ```python >>> x ** np.array([0., 1., 2.]) array([[ 1., 1., 4.], @@ -84,14 +84,14 @@ array([[ 1., 1., 4.], [ 1., 7., 64.]]) ``` -Basic indexing allows us to access multi-dimensional slices of `x`: +基本索引(basic indexing)允许我们获得 `x` 的多维度切片: ```python >>> x[:2, :3] array([[0, 1, 2], [3, 4, 5]]) ``` -Advanced indexing can be used to access all even-valued entries of `x`; let's update `x` so that all of its even-valued entries are multiplied by -1: +进阶索引可以用来获取 `x` 中所有的偶数;让我们更新 `x` 来让它所有的偶数都乘以-1吧: ```python >>> x[x % 2 == 0] *= -1 @@ -101,11 +101,11 @@ array([[ 0, 1, -2], [-6, 7, -8]]) ``` -By the end of this module, these code snippets should make good sense, and NumPy's tremendous utility should be clear. +在本模组结尾,这些代码片段都将会成为你理解范围内,且NumPy的强大功能也将得到充分的展示。 -## Links to Official Documentation +## 官方说明文档链接 -- [The N-dimensional array](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) -- [NumPy Basics](https://docs.scipy.org/doc/numpy/user/basics.html#numpy-basics) -- [NumPy reference](https://docs.scipy.org/doc/numpy/reference/index.html) +- [N维数组](https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) +- [NumPy基础](https://docs.scipy.org/doc/numpy/user/basics.html#numpy-basics) +- [NumPy参考](https://docs.scipy.org/doc/numpy/reference/index.html) diff --git a/Python/Module3_IntroducingNumpy/Problems/Approximating_pi.ipynb b/Python/Module3_IntroducingNumpy/Problems/Approximating_pi.ipynb index ad78816..fea551c 100644 --- a/Python/Module3_IntroducingNumpy/Problems/Approximating_pi.ipynb +++ b/Python/Module3_IntroducingNumpy/Problems/Approximating_pi.ipynb @@ -4,12 +4,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Playing Darts and Estimating Pi\n", - "You and some friends are playing darts. You all are **very** bad at darts. Each throw is guaranteed to hit the square board depicted below, but otherwise each throw will land in a completely random position within the square. To entertain yourself during this pathetic display, you decide to use this as an opportunity to estimate the irrational number $\\pi \\approx 3.14159$.\n", + "# 掷镖游戏和约算Pi\n", + "你和你的几个朋友在一起玩飞镖。你们对这个游戏都**非常**不会玩。你们丢的每一镖一定会击中以下的正方形板,但是除此之外每次丢的镖会随机落到正方形中的任何位置。为了在展现你垃圾技巧的同时自娱自乐,你决定这是一个约算无理数 $\\pi \\approx 3.14159$ 的好机会。\n", "\n", "![A dart board](attachments/circle_square_small.png)\n", "\n", - "Because each throw falls randomly within the square, you realize that the probability of a dart landing within the circle is given by the ratio of the circle's area to the square's area:\n", + "因为你的每一镖都会随机落到正方形中,你发现镖落到圆的几率等于圆面积相比正方形面积的比例:\n", "\n", "\\begin{equation}\n", "P_{circle} = \\frac{Area_{circle}}{Area_{square}} = \\frac{\\pi r^2}{(2r)^2}\n", @@ -20,56 +20,56 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Furthermore, we can interpret $P_{circle}$ as being approximated by the fraction of darts thrown that land in the circle. Thus, we find:\n", + "更进一步,我们可以通过镖落入圆形的比例来约算 $P_{circle}$。因此,我们写出以下公式:\n", "\n", "\\begin{equation}\n", "\\frac{N_{circle}}{N_{total}} \\approx \\frac{\\pi r^2}{(2r)^2} = \\frac{\\pi}{4}\n", "\\end{equation}\n", "\n", - "where $N_{total}$ is the total number of darts thrown, and $N_{circle}$ is the number of darts that land within the circle. Thus simply by keeping tally of where the darts land, you can begin to estimate the value of $\\pi$!\n", + "其中 $N_{total}$ 是总共丢的飞镖数,$N_{circle}$ 是落入圆中的飞镖数。因此,通过计算飞镖落到的不同位置的次数,你可以开始约算 $\\pi$ 的值!\n", "\n", - "## Problem 1\n", + "## 问题1\n", "\n", - "Write code that simulates the dart throwing and tallying process, and keep a running estimate of $\\pi$ as \"darts are being thrown\". For simplicity, you can assume that the board is centered at $(0, 0)$, and that $r = 1$ (the radius of the circle). Use `numpy.random.rand` ([link to docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html)) to randomly generate the positions on the board where the darts land. Do this for $N = 10,000$ darts in total. For each dart thrown determine whether or not it landed within the circle, and update your estimate of $\\pi$ according to the formula: $N_{circle} / N_{total} \\approx \\pi / 4$\n", + "编写代码来模拟丢掷飞镖和数其是否落入圆中的代码,并“在飞镖被丢掷”的同时计算实时的 $\\pi$ 值。为了简单性,你可以假设板的中心在 $(0, 0)$,且 $r = 1$(圆的半径)。使用 `numpy.random.rand`([说明文档链接](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html))来随机生成飞镖落到板上的位置。为总共 $N = 10,000$ 个镖进行以上计算。为每个丢出的镖决定其是否落入了圆中,并根据以下公式更新你对 $\\pi$ 的估测值:$N_{circle} / N_{total} \\approx \\pi / 4$\n", "\n", - "Keep in mind that each dart can land in $(x \\in [-1, 1], y \\in [-1, 1])$ and that a dart that lands at $(x, y)$ falls within the circle if \n", + "请记住,每个镖可以落入的范围是 $(x \\in [-1, 1], y \\in [-1, 1])$,而一个落到 $(x, y)$ 的镖只有满足以下条件才算是落入到了圆中:\n", "\n", "\\begin{equation}\n", "\\sqrt{x^2 + y^2} < 1\n", "\\end{equation}\n", "\n", - "You can start this problem by writing a solution that uses explicit for-loops to help make clear the solution. That being said, you should strive to write a fully-vectorized solution (i.e. compute the running estimation of $\\pi$ during $10,000$ dart throws without any explicit for-loops)." + "你可以首先通过显式for循环来编写一个直观的解。虽然如此,你应该努力编写一个完全矢量化的解(也就是说,不使用任何显式for循环来计算 $10,000$ 次丢镖中每丢一镖后的 $\\pi$ 约算值)。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Relevant Reading\n", + "## 相关阅读\n", "\n", - "You will need to be familiar with NumPy's [vectorized operations](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html) and with [summing over axes](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html#Specifying-the-axis-Keyword-Argument-in-Sequential-NumPy-Functions). It will also likely be useful to leverage [boolean indexing](http://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/AdvancedIndexing.html#Boolean-Array-Indexing). \n", + "你会需要熟悉NumPy的[矢量化操作](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html)和[根据轴求和](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html#Specifying-the-axis-Keyword-Argument-in-Sequential-NumPy-Functions)。你也很可能会发现[布尔索引](http://cn.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/AdvancedIndexing.html#Boolean-Array-Indexing)很有用。\n", "\n", - "It is strongly recommended that you use matplotlib to visualize your running estimate of $\\pi$. You can refer to [this segment of PLYMI](http://www.pythonlikeyoumeanit.com/Module5_OddsAndEnds/Matplotlib.html#Plotting-and-Saving-a-Figure) to see how to create a simple line plot." + "这里强烈建议你使用matplotlib来可视化你对 $\\pi$ 每一轮后的约算值。你可以参阅[PLYMI的这一小节](http://cn.pythonlikeyoumeanit.com/Module5_OddsAndEnds/Matplotlib.html#Plotting-and-Saving-a-Figure)来学习如何创建一个简单的线图。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Tips\n", + "## 提示\n", "\n", - "It is helpful to know about NumPy's [cumulative-sum function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html), `numpy.cumsum`. This is useful for keeping a running tally - i.e. keeping the history of the number of darts that have fallen within the circle, and not just the current count." + "了解NumPy的[累计和函数](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) `numpy.cumsum` 会很有用。这对计算每一轮后的总数很有用——也就是说,这可以帮助你计算每一轮后总共落入圆中的镖的数量,而不仅仅是这一轮是否在圆中。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Solution (Unvectorized)\n", + "## 解(未矢量化)\n", "\n", - "To start, we want to generate the $(x, y)$ coordinates for our $N = 10,000$ darts. Using `numpy.random.rand(N, 2)`, we can generate a 2D array with $N$ rows - each row contains the $(x, y)$ coordinate for a single dart. \n", + "首先,我们想要生成 $N = 10,000$ 镖的 $(x, y)$ 坐标。使用 `numpy.random.rand(N, 2)`,我们可以生成有 $N$ 行的2维数组——每一行包含着一镖的 $(x, y)$ 坐标。\n", "\n", - "We want the $x$ and $y$ coordinate of each dart to fall within $[-1, 1]$, respectively. `numpy.random.rand` generates numbers on the interval $[0, 1)$. We can multiply the generated numbers by two and then subtract one to instead generate numbers on the interval $[-1, 1)$." + "我们想要每一镖的 $x$ 和 $y$ 坐标落入 $[-1, 1]$。`numpy.random.rand` 生成在范围 $[0, 1)$ 中的数。我们可以对生成的数乘以2并减去1来使得生成树随机落入 $[-1, 1)$。" ] }, { @@ -80,14 +80,14 @@ "source": [ "import numpy as np\n", "N = 10000\n", - "dart_positions = 2 * np.random.rand(N, 2) - 1 # generates numbers in [-1, 1]" + "dart_positions = 2 * np.random.rand(N, 2) - 1 # 生成 [-1, 1] 中的数字" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we can loop over the dart positions, determine if whether a given dart fell within the circle, and update $N_{circle}$ accordingly." + "现在,我们可以循环迭代所有的镖位置,决定其是否在圆中,并根据结果更新 $N_{circle}$。" ] }, { @@ -96,20 +96,20 @@ "metadata": {}, "outputs": [], "source": [ - "Ncircle = [0] # start the count with 0 to make our loop-logic easier\n", + "Ncircle = [0] # 将首位值设为0来简化循环中的逻辑\n", "\n", "for x,y in dart_positions: \n", " if np.sqrt(x**2 + y**2) < 1:\n", - " Ncircle.append(Ncircle[-1] + 1) # another dart has fallen in the circle\n", + " Ncircle.append(Ncircle[-1] + 1) # 镖落入了圆中\n", " else:\n", - " Ncircle.append(Ncircle[-1]) # the dart fell outside of the circle - Ncircle is unchanged" + " Ncircle.append(Ncircle[-1]) # 镖落入了圆外——Ncircle没有变化" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now lets use our list, `Ncircle`, to compute the running approximation for $\\pi$. We will " + "现在,让我们使用我们的列表 `Ncircle` 来计算每一轮后对 $\\pi$ 的约算值。" ] }, { @@ -120,8 +120,8 @@ "source": [ "running_estimate = []\n", "\n", - "for n_total, n_circle in enumerate(Ncircle[1:]): # skip the inital 0-count\n", - " # n_total starts at 0, so we need to add 1\n", + "for n_total, n_circle in enumerate(Ncircle[1:]): # 跳过第一个的零值\n", + " # n_total将从0开始,所以我们需要加1\n", " running_estimate.append(4 * n_circle / (n_total + 1))" ] }, @@ -129,7 +129,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Let's print our estimate for our first 10 throws and our last 10 throws. We should see that our estimate is extremely crude and noisy for the first 10 throws and is much more tightly bound for the last 10 throws." + "让我们打印我们对前10镖后和最后10镖后的约算值。我们应该能注意在前10镖后的约值非常不精确且受噪声影响,而在最后10镖后明显更加紧密。" ] }, { @@ -140,16 +140,7 @@ { "data": { "text/plain": [ - "[4.0,\n", - " 4.0,\n", - " 2.6666666666666665,\n", - " 2.0,\n", - " 2.4,\n", - " 2.6666666666666665,\n", - " 2.2857142857142856,\n", - " 2.5,\n", - " 2.6666666666666665,\n", - " 2.8]" + "[4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]" ] }, "execution_count": 4, @@ -169,16 +160,16 @@ { "data": { "text/plain": [ - "[3.1184065659093183,\n", - " 3.1184947958366696,\n", - " 3.118583008105674,\n", - " 3.118671202721633,\n", - " 3.1187593796898447,\n", - " 3.118847539015606,\n", - " 3.1189356807042112,\n", - " 3.119023804760952,\n", - " 3.119111911191119,\n", - " 3.1192]" + "[3.1380242217996197,\n", + " 3.1381104883907125,\n", + " 3.1381967377164015,\n", + " 3.1378827296377825,\n", + " 3.1379689844922463,\n", + " 3.1380552220888354,\n", + " 3.137741322396719,\n", + " 3.1378275655131027,\n", + " 3.137913791379138,\n", + " 3.138]" ] }, "execution_count": 5, @@ -194,16 +185,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Solution (Vectorized)" + "## 解(矢量化)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "To start, we want to generate the $(x, y)$ coordinates for our $N = 10,000$ darts. Using `numpy.random.rand(N, 2)`, we can generate a 2D array with $N$ rows - each row contains the $(x, y)$ coordinate for a single dart. \n", + "首先,我们想要生成 $N = 10,000$ 镖的 $(x, y)$ 坐标。使用 `numpy.random.rand(N, 2)`,我们可以生成有 $N$ 行的2维数组——每一行包含着一镖的 $(x, y)$ 坐标。\n", "\n", - "We want the $x$ and $y$ coordinate of each dart to fall within $[-1, 1]$, respectively. `numpy.random.rand` generates numbers on the interval $[0, 1)$. We can multiply the generated numbers by two and then subtract one to instead generate numbers on the interval $[-1, 1)$." + "我们想要每一镖的 $x$ 和 $y$ 坐标落入 $[-1, 1]$。`numpy.random.rand` 生成在范围 $[0, 1)$ 中的数。我们可以对生成的数乘以2并减去1来使得生成树随机落入 $[-1, 1)$。" ] }, { @@ -214,14 +205,14 @@ "source": [ "import numpy as np\n", "N = 10000\n", - "dart_positions = 2 * np.random.rand(N, 2) - 1 # generates numbers in [-1, 1]" + "dart_positions = 2 * np.random.rand(N, 2) - 1 # 生成在 [-1, 1] 中的数字" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we want to compute the distance from the origin, $\\sqrt{x^2 + y^2}$, for every dart in `dart_positions`. We can do this by squaring each element of `dart_positions` and summing across its *columns* (axis-1), and then taking the square root of the result. This will produce a shape-$(N,)$ array that stores the distance of each dart from the origin." + "现在,我们将要为 `dart_positions` 中的每一镖计算和原点的距离 $\\sqrt{x^2 + y^2}$。我们可以平方 `dart_positions` 中的每一个值并顺着它的*列*(轴1)求和,然后平方根其结果。这将产生一个形状为 $(N,)$ 的储存每一镖和原点距离的数组。" ] }, { @@ -230,21 +221,21 @@ "metadata": {}, "outputs": [], "source": [ - "dist_from_origin = np.sqrt((dart_positions**2).sum(axis=1)) # shape-(N,) array" + "dist_from_origin = np.sqrt((dart_positions**2).sum(axis=1)) # 形状为 (N,) 的数组" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "More concisely, you can use the built-in function `np.linalg.norm` to the same effect." + "你也可以使用内置的 `np.linalg.norm` 来编写更加简短的等值代码。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we want to determine which of those darts fall within the circle. That is, find where $\\sqrt{x^2 + y^2} < 1$. We can simply use `<` to perform an elementwise comparison. This will produce a *boolean-valued* array whose value is `True` for each dart that fell within the circle and `False` for those that didn't." + "现在,我们想要确认这些镖是否落入圆中。也就是说,我们想要求 $\\sqrt{x^2 + y^2} < 1$ 是否为真。我们可以直接使用 `<` 来对每个成员进行对比。这将返回一个*布尔值*数组,其值在镖落入圆中时为 `True` 而不落入圆中时为 `False`。" ] }, { @@ -253,14 +244,14 @@ "metadata": {}, "outputs": [], "source": [ - "is_in_circle = dist_from_origin < 1 # shape-(N,) boolean array" + "is_in_circle = dist_from_origin < 1 # 形状为 (N,) 的布尔数组" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Finally, we want to compute the total number of darts that had landed within the circle at each given point in the sequence of throws. [Recall that](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Boolean-Objects-are-Integers) `True` behaves like `1` and `False` behaves like `0`. Thus we can perform a cumulative sum on `in_circle` to perform this tally." + "最后,我们想要计算每一轮后落入圆中的总镖数。[请回忆](https://cn.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Boolean-Objects-are-Integers),`True` 的行为类似 `1`,而 `False` 的行为类似 `0`。因此,我们可以对 `in_circle` 进行累计和来计算这个。" ] }, { @@ -269,7 +260,7 @@ "metadata": {}, "outputs": [], "source": [ - "# cumulative sum: num_in_circle[i] = sum(is_in_circle[:i])\n", + "# 累计和:num_in_circle[i] = sum(is_in_circle[:i])\n", "num_in_circle = np.cumsum(is_in_circle)\n", "\n", "num_thrown = np.arange(1, N+1) # 1, 2, ..., N" @@ -279,7 +270,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Finally we can compute our approximated value of $\\pi$ for each dart thrown via $N_{circle} / N_{total} \\approx \\pi / 4$." + "最后,我们可以通过 $N_{circle} / N_{total} \\approx \\pi / 4$ 计算每一镖后对 $\\pi$ 的预估值。" ] }, { @@ -295,13 +286,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Let's inspect our results by plotting them. We will create a simple line plot, and will include the actual value of pi as a dashed horizontal line. Because we are throwing so many darts, it is useful to plot the number of darts thrown on a log-scale. This will let us to see how our approximation improves on the scale of throwing tens of darts versus hundred versus thousands, etc." + "让我们通过绘制结果来查看它们。我们将会创建一个简单的线图并将pi的正确值作为虚的横线画出。因为我们丢了那么多镖,将镖数绘制在一个对数标尺(log scale)中会更加直观。这将允许我们查看我们的预估是如何在丢几十次和几百次和几千次等等后提升的。" ] }, { "cell_type": "code", "execution_count": 12, - "metadata": {}, + "metadata": { + "scrolled": false + }, "outputs": [ { "data": { @@ -316,7 +309,7 @@ " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", - " alert('Your browser does not have WebSocket support.' +\n", + " alert('Your browser does not have WebSocket support. ' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", @@ -533,7 +526,7 @@ "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", - " var nav_element = $('
')\n", + " var nav_element = $('
');\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", @@ -590,7 +583,7 @@ " var fmt = mpl.extensions[ind];\n", " var option = $(\n", " '