← 学习库 Think Python (2e) · 中英对照 目录

Chapter 10  Lists 第 10 章 列表

本页译自 Think Python 2e(Allen B. Downey)· Chapter 10 Lists。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。

10.1 A list is a sequence 10.1 列表是序列

Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items.

与字符串一样,列表也是一组值的序列。字符串里的值是字符,列表里的值则可以是任意类型。列表里的值称为元素,有时也叫条目(item)。

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and [):

创建新列表有几种方式,最简单的是把元素放进方括号([[)里:
[00000008

The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and (lo!) another list:

第一个例子是一个包含四个整数的列表,第二个是包含三个字符串的列表。列表里的元素不必是同一类型。下面这个列表包含了一个字符串、一个浮点数、一个整数,以及(瞧!)另一个列表:
[00000009

A list within another list is nested.

一个列表嵌在另一个列表里,就称为嵌套的。

A list that contains no elements is called an empty list; you can create one with empty brackets, [0.

不含任何元素的列表称为空列表;用空的方括号 [0 就能创建一个。

As you might expect, you can assign list values to variables:

不出所料,你可以把列表赋值给变量:
[00000012

10.2 Lists are mutable 10.2 列表是可变的

The syntax for accessing the elements of a list is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:

访问列表元素的语法与访问字符串字符相同——都是方括号运算符。方括号里的表达式指定索引。记住索引从 0 开始:
[00000013

Unlike strings, lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.

与字符串不同,列表是可变的。当方括号运算符出现在赋值语句左边时,它指定的是列表里将被赋值的那个元素。
[00000014

The one-eth element of [000000, which used to be 123, is now 5.

[000000 里原本是 123 的那个元素,现在变成了 5。

You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements. Figure 10.1 shows the state diagram for [000000, [000000 and [0000:

可以把列表看作索引与元素之间的关系。这种关系称为映射:每个索引「映射到」其中一个元素。图 10.1 展示了 [000000、[000000 和 [0000 的状态图:

Figure 10.1: State diagram.

图 10.1:状态图(原书插图未收录)

Lists are represented by boxes with the word “list” outside and the elements of the list inside. [000000 refers to a list with three elements indexed 0, 1 and 2. [000000 contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5. [0000 refers to a list with no elements.

列表用方框表示,框外写着「list」,框内是列表的元素。[000000 指向一个有 0、1、2 三个索引的列表。[000000 包含两个元素;图中显示第二个元素的值从 123 被改成了 5。[0000 指向一个没有任何元素的列表。

List indices work the same way as string indices:

列表的索引与字符串索引规则相同:

The [0 operator also works on lists.

[0 运算符对列表同样适用。
[00000033

10.3 Traversing a list 10.3 遍历列表

The most common way to traverse the elements of a list is with a [00 loop. The syntax is the same as for strings:

遍历列表元素最常用的方法是 [00 循环,语法与遍历字符串相同:
[00000036

This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions [0000 and [00:

如果只是读取元素,这样写很好用。但如果你想写入或更新元素,就需要用到索引。常用做法是将 [0000 和 [00 两个函数结合起来:
[00000041

This loop traverses the list and updates each element. [00 returns the number of elements in the list. [0000 returns a list of indices from 0 to n−1, where n is the length of the list. Each time through the loop [ gets the index of the next element. The assignment statement in the body uses [ to read the old value of the element and to assign the new value.

这个循环遍历列表并更新每个元素。[00 返回列表里元素的个数。[0000 返回一个从 0 到 n−1 的索引列表,其中 n 是列表长度。每轮循环 [ 取到下一个元素的索引。循环体里的赋值语句用 [ 读取元素的旧值并赋入新值。

A [00 loop over an empty list never executes the body:

对空列表执行的 [00 循环,循环体永远不会运行:
[00000052

Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:

虽然列表可以包含另一个列表,但嵌套列表仍然只算作一个元素。下面这个列表的长度是 4:
[00000053

10.4 List operations 10.4 列表运算

The [ operator concatenates lists:

[ 运算符把列表拼接起来:
[00000056

Similarly, the [ operator repeats a list a given number of times:

类似地,[ 运算符把一个列表重复指定次数:
[00000059

The first example repeats [00 four times. The second example repeats the list [00000061 three times.

第一个例子把 [00 重复了四次,第二个例子把列表 [00000063 重复了三次。

10.5 List slices 10.5 列表切片

The slice operator also works on lists:

切片运算符对列表同样适用:
[00000064

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.

省略第一个索引,切片就从开头开始;省略第二个,切片就一直取到末尾。两个都省略,切片就是整个列表的副本。
[00000065

Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle or mutilate lists.

由于列表是可变的,在执行那些会折叠、扭转或破坏列表的操作之前,先做一个副本往往很有用。

A slice operator on the left side of an assignment can update multiple elements:

赋值语句左边的切片运算符可以一次更新多个元素:
[00000066

10.6 List methods 10.6 列表方法

Python provides methods that operate on lists. For example, [00000 adds a new element to the end of a list:

Python 提供了操作列表的方法。例如,[00000 在列表末尾添加一个新元素:
[00000069

[00000 takes a list as an argument and appends all of the elements:

[00000 接受一个列表作为参数,把它的所有元素都追加进来:
[00000072

This example leaves [0 unmodified.

这个例子中 [0 没有被改动。

[000 arranges the elements of the list from low to high:

[000 把列表里的元素按从低到高排列:
[00000077

List methods are all void; they modify the list and return [000. If you accidentally write [00000079, you will be disappointed with the result.

列表方法都是无返回值函数:它们修改列表并返回 [000。如果你不小心写成 [00000081,结果会让你大失所望。

10.7 Map, filter and reduce 10.7 映射、筛选与归约

To add up all the numbers in a list, you can use a loop like this:

要把列表里所有数字相加,可以像这样用循环:
[00000082

[0000 is initialized to 0. Each time through the loop, [ gets one element from the list. The [0 operator provides a short way to update a variable. This augmented assignment statement:

[0000 初始化为 0。每轮循环 [ 取列表里的一个元素。[0 运算符提供了一种更新变量的简写方式。这条增量赋值语句:
[00000089

is equivalent to:

等价于:
[00000090

As the loop executes, [0000 accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.

循环执行时,[0000 不断累积各元素之和;像这样使用的变量有时称为累加器

Adding up the elements of a list is such a common operation that Python provides it as a built-in function, [00:

把列表元素相加实在太常用了,Python 干脆把它做成了内置函数 [00:
[00000095

An operation like this that combines a sequence of elements into a single value is sometimes called reduce.

像这样把一组元素合并成单个值的操作,有时称为归约(reduce)。

Exercise 1

习题 1

Write a function called [00000096 that takes a nested list of integers and add up the elements from all of the nested lists.

写一个名为 [00000097 的函数,接受一个嵌套的整数列表,把所有嵌套列表里的元素都加起来。

Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings:

有时你在遍历一个列表的同时想构造另一个列表。例如,下面这个函数接受一个字符串列表,返回一个新的列表,其中包含首字母大写的字符串:
[00000098

[00 is initialized with an empty list; each time through the loop, we append the next element. So [00 is another kind of accumulator.

[00 用一个空列表初始化;每轮循环我们把下一个元素追加进去。所以 [00 是另一种累加器。

An operation like [00000103 is sometimes called a map because it “maps” a function (in this case the method [00000104) onto each of the elements in a sequence.

[00000105 这样的操作有时称为映射(map),因为它把一个函数(这里是 [00000106 方法)「映射」到序列里的每个元素上。

Exercise 2

习题 2

Use [00000107 to write a function named [00000108 that takes a nested list of strings and returns a new nested list with all strings capitalized.

[00000109 写一个名为 [00000110 的函数,接受一个嵌套的字符串列表,返回一个新的嵌套列表,其中所有字符串都首字母大写。

Another common operation is to select some of the elements from a list and return a sublist. For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:

另一种常见操作是从列表中挑出部分元素,返回一个子列表。例如,下面这个函数接受一个字符串列表,返回只包含大写字符串的列表:
[00000111

[000001 is a string method that returns [000 if the string contains only upper case letters.

[000001 是一个字符串方法,当字符串只包含大写字母时返回 [000。

An operation like [00000116 is called a filter because it selects some of the elements and filters out the others.

[00000117 这样的操作称为筛选(filter),因为它选中部分元素、滤掉其余元素。

Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function [00 and an operator called a “list comprehension.”

大多数常见的列表操作都能表达为映射、筛选和归约的组合。因为这些操作太常用,Python 提供了专门的语言特性来支持它们,包括内置函数 [00 和一种叫「列表推导式」的运算符。

Exercise 3

习题 3

Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example, the cumulative sum of [00000120 is [00000121.

写一个函数,接受一个数字列表,返回累加和;也就是说,返回一个新列表,其中第 i 个元素是原列表前 i+1 个元素之和。例如,[00000122 的累加和是 [00000123。

10.8 Deleting elements 10.8 删除元素

There are several ways to delete elements from a list. If you know the index of the element you want, you can use [00:

从列表里删除元素有几种方式。如果你知道要删元素的索引,可以用 [00:
[00000126

[00 modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.

[00 会修改列表并返回被移除的元素。如果不给索引,它会删除并返回最后一个元素。

If you don’t need the removed value, you can use the [00 operator:

如果你不需要那个被删掉的值,可以用 [00 运算符:
[00000131

If you know the element you want to remove (but not the index), you can use [00000:

如果你知道要删的是哪个元素(但不知道索引),可以用 [00000:
[00000134

The return value from [00000 is [000.

[00000 的返回值是 [000。

To remove more than one element, you can use [00 with a slice index:

要一次删除多个元素,可以配合切片索引使用 [00:
[00000141

As usual, the slice selects all the elements up to, but not including, the second index.

和往常一样,切片选中第二个索引之前(但不含)的所有元素。

Exercise 4

习题 4

Write a function called [00000 that takes a list and returns a new list that contains all but the first and last elements. So [00000143 should return [0000.

写一个名为 [00000 的函数,接受一个列表,返回一个新列表,其中包含除首尾元素外的所有元素。也就是说,[00000146 应返回 [0000。

Exercise 5

习题 5

Write a function called [000 that takes a list, modifies it by removing the first and last elements, and returns [000.

写一个名为 [000 的函数,接受一个列表,通过删除首尾元素来修改它,并返回 [000。

10.9 Lists and strings 10.9 列表与字符串

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use [000:

字符串是字符的序列,列表是值的序列,但字符列表并不等于字符串。要把字符串转换成字符列表,可以用 [000:
[00000154

Because [000 is the name of a built-in function, you should avoid using it as a variable name. I also avoid [ because it looks too much like [. So that’s why I use [.

因为 [000 是内置函数的名字,你应避免把它用作变量名。我也不用 [,因为它太像 [ 了。所以我就用 [

The [000 function breaks a string into individual letters. If you want to break a string into words, you can use the [0000 method:

[000 函数把一个字符串拆成单个字母。如果你想把一个字符串拆成单词,可以用 [0000 方法:
[00000167

An optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:

一个可选的实参叫分隔符(delimiter),用来指定哪些字符作为单词边界。下面这个例子用连字符作为分隔符:
[00000168

[000 is the inverse of [0000. It takes a list of strings and concatenates the elements. [000 is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:

[000 是 [0000 的逆操作。它接受一个字符串列表并把元素拼接起来。[000 是字符串方法,所以你得在分隔符上调用它,并把列表作为参数传入:
[00000175

In this case the delimiter is a space character, so [000 puts a space between words. To concatenate strings without spaces, you can use the empty string, [0, as a delimiter.

这里分隔符是一个空格字符,所以 [000 在单词之间插了一个空格。要把字符串无缝拼接,可以用空字符串 [0 作为分隔符。

10.10 Objects and values 10.10 对象与值

If we execute these assignment statements:

如果我们执行下面这些赋值语句:
[00000180

We know that [ and [ both refer to a string, but we don’t know whether they refer to the same string. There are two possible states, shown in Figure 10.2.

我们知道 [[ 都指向一个字符串,但不知道它们指向的是同一个字符串。有两种可能的状态,如图 10.2 所示。

Figure 10.2: State diagram.

图 10.2:状态图(原书插图未收录)

In one case, [ and [ refer to two different objects that have the same value. In the second case, they refer to the same object.

其中一种情况是,[[ 指向两个值相同但不同的对象。另一种情况是,它们指向同一个对象。

To check whether two variables refer to the same object, you can use the [0 operator.

要检查两个变量是否指向同一个对象,可以用 [0 运算符。
[00000191

In this example, Python only created one string object, and both [ and [ refer to it.

这个例子里,Python 只创建了一个字符串对象,[[ 都指向它。

But when you create two lists, you get two objects:

但当你创建两个列表时,会得到两个对象:
[00000196

So the state diagram looks like Figure 10.3.

所以状态图如图 10.3 所示。

Figure 10.3: State diagram.

图 10.3:状态图(原书插图未收录)

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

这种情况我们会说这两个列表是等价的,因为它们有相同的元素;但不是同一的,因为它们不是同一个对象。如果两个对象同一,它们必然等价;但等价,未必同一。

Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you execute [000001, you get a list object whose value is a sequence of integers. If another list has the same elements, we say it has the same value, but it is not the same object.

到目前为止,我们一直混用「对象」和「值」,但更准确的说法是:对象拥有值。执行 [000001 得到的是一个列表对象,它的值是整数序列。如果另一个列表有相同的元素,我们说它的值相同,但它不是同一个对象。

10.11 Aliasing 10.11 别名

If [ refers to an object and you assign [0000, then both variables refer to the same object:

如果 [ 指向一个对象,你又赋值 [0000,那么两个变量就指向同一个对象:
[00000203

The state diagram looks like Figure 10.4.

状态图如图 10.4 所示。

Figure 10.4: State diagram.

图 10.4:状态图(原书插图未收录)

The association of a variable with an object is called a reference. In this example, there are two references to the same object.

变量与对象之间的关联称为引用(reference)。在这个例子中,同一个对象有两个引用。

An object with more than one reference has more than one name, so we say that the object is aliased.

一个对象有多个引用,就有了多个名字,所以我们说这个对象被取了别名(aliased)。

If the aliased object is mutable, changes made with one alias affect the other:

如果取了别名的对象是可变的,通过一个别名做的修改会影响另一个:
[00000204

Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.

虽然这种特性有时好用,但也容易出错。一般来说,处理可变对象时,避免取别名更安全。

For immutable objects like strings, aliasing is not as much of a problem. In this example:

对于字符串这类不可变对象,别名问题没那么严重。例如:
[00000205

It almost never makes a difference whether [ and [ refer to the same string or not.

[[ 到底指向同一个字符串与否,几乎没有任何区别。

10.12 List arguments 10.12 列表实参

When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, [00000210 removes the first element from a list:

当你把一个列表传给函数时,函数拿到的是该列表的引用。如果函数修改了列表形参,调用方会看到这个改动。例如,[00000211 删除列表的第一个元素:
[00000212

Here’s how it is used:

用法如下:
[00000213

The parameter [ and the variable [000002 are aliases for the same object. The stack diagram looks like Figure 10.5.

形参 [ 和变量 [000002 是同一个对象的两个别名。栈图如图 10.5 所示。

Figure 10.5: Stack diagram.

图 10.5:栈图(原书插图未收录)

Since the list is shared by two frames, I drew it between them.

因为该列表被两个栈帧共享,我把它们画在两者之间。

It is important to distinguish between operations that modify lists and operations that create new lists. For example, the [00000 method modifies a list, but the [ operator creates a new list:

区分「修改列表的操作」和「创建新列表的操作」很重要。例如,[00000 方法修改列表,而 [ 运算符创建新列表:
[00000222

This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:

当你写「本应修改列表」的函数时,这个区别很关键。例如,下面这个函数并没有删除列表的头部:
[00000223

The slice operator creates a new list and the assignment makes [ refer to it, but none of that has any effect on the list that was passed as an argument.

切片运算符创建了一个新列表,赋值让 [ 指向它,但这些对作为实参传进来的列表没有任何影响。

An alternative is to write a function that creates and returns a new list. For example, [000 returns all but the first element of a list:

另一种做法是写一个创建并返回新列表的函数。例如,[000 返回列表里除第一个元素外的所有元素:
[00000228

This function leaves the original list unmodified. Here’s how it is used:

这个函数不会改动原列表。用法如下:
[00000229

10.13 Debugging 10.13 调试

Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:

粗心使用列表(以及其他可变对象)可能导致你花上大把时间调试。下面是一些常见陷阱和规避方法:
  1. Don’t forget that most list methods modify the argument and return [000. This is the opposite of the string methods, which return a new string and leave the original alone. If you are used to writing string code like this: [00000231 It is tempting to write list code like this: [00000232 Because [000 returns [000, the next operation you perform with [ is likely to fail. Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode. The methods and operators that lists share with other sequences (like strings) are documented at [00000236. The methods and operators that only apply to mutable sequences are documented at [00000237.
  2. Pick an idiom and stick with it. Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use [00, [00000, [00, or even a slice assignment. To add an element, you can use the [00000 method or the [ operator. Assuming that [ is a list and [ is a list element, these are right: [00000245 And these are wrong: [00000246 Try out each of these examples in interactive mode to make sure you understand what they do. Notice that only the last one causes a runtime error; the other three are legal, but they do the wrong thing.
  3. Make copies to avoid aliasing. If you want to use a method like [000 that modifies the argument, but you need to keep the original list as well, you can make a copy. [00000248 In this example you could also use the built-in function [00000, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using [00000 as a variable name!
  1. 别忘了,大多数列表方法会修改实参并返回 [000。这与字符串方法正好相反——字符串方法会返回一个新字符串,原字符串不动。 如果你习惯这么写字符串代码: [00000252 就很容易写出这样的列表代码: [00000253 因为 [000 返回 [000,接下来对 [ 执行的操作很可能会失败。 在使用列表方法和运算符之前,应仔细阅读文档,并在交互模式下测试它们。列表与其他序列(如字符串)共享的方法和运算符,文档在 [00000257。只适用于可变序列的方法和运算符,文档在 [00000258。
  2. 选定一种惯用法并坚持下去。 列表的问题之一,是做事的方式太多了。例如,要从列表里删元素,可以用 [00、[00000、[00,甚至切片赋值。 要添加元素,可以用 [00000 方法或 [ 运算符。假设 [ 是列表、[ 是列表元素,下面这样写是对的: [00000266 下面这样写是错的: [00000267 请在交互模式下逐个试一遍,确保你明白它们各自的行为。注意只有最后一种会引发运行时错误;另外三种语法合法,但做的事不对。
  3. 用副本避免别名。 如果你想用 [000 这种会修改实参的方法,又想保留原列表,可以先做个副本。 [00000269 这个例子里你也可以用内置函数 [00000,它返回一个排好序的新列表,原列表不动。但那样的话,别把 [00000 用作变量名!

10.14 Glossary 10.14 术语表

list:
A sequence of values.
element:
One of the values in a list (or other sequence), also called items.
index:
An integer value that indicates an element in a list.
nested list:
A list that is an element of another list.
list traversal:
The sequential accessing of each element in a list.
mapping:
A relationship in which each element of one set corresponds to an element of another set. For example, a list is a mapping from indices to elements.
accumulator:
A variable used in a loop to add up or accumulate a result.
augmented assignment:
A statement that updates the value of a variable using an operator like [0.
reduce:
A processing pattern that traverses a sequence and accumulates the elements into a single result.
map:
A processing pattern that traverses a sequence and performs an operation on each element.
filter:
A processing pattern that traverses a list and selects the elements that satisfy some criterion.
object:
Something a variable can refer to. An object has a type and a value.
equivalent:
Having the same value.
identical:
Being the same object (which implies equivalence).
reference:
The association between a variable and its value.
aliasing:
A circumstance where two or more variables refer to the same object.
delimiter:
A character or string used to indicate where a string should be split.
list 列表:
一组值的序列。
element 元素:
列表(或其他序列)中的某个值,也叫条目(item)。
index 索引:
表示列表中某个元素的整数值。
nested list 嵌套列表:
作为另一个列表的元素的列表。
list traversal 列表遍历:
按顺序访问列表里的每个元素。
mapping 映射:
一种关系,其中一个集合的每个元素对应另一个集合的一个元素。例如,列表就是「索引到元素」的映射。
accumulator 累加器:
循环中用来累加结果的变量。
augmented assignment 增量赋值:
[0 这类运算符更新变量值的语句。
reduce 归约:
一种处理模式:遍历序列,把元素累积成单个结果。
map 映射:
一种处理模式:遍历序列,对每个元素执行某个操作。
filter 筛选:
一种处理模式:遍历列表,选出满足某些条件的元素。
object 对象:
变量可以指向的东西。一个对象拥有类型与值。
equivalent 等价:
具有相同的值。
identical 同一:
是同一个对象(这蕴含等价)。
reference 引用:
变量与其值之间的关联。
aliasing 别名:
两个或多个变量指向同一个对象的情况。
delimiter 分隔符:
用来指示字符串应在何处拆分的字符或字符串。

10.15 Exercises 10.15 习题

Exercise 6

习题 6

Write a function called [00000274 that takes a list as a parameter and returns [000 if the list is sorted in ascending order and [0000 otherwise. You can assume (as a precondition) that the elements of the list can be compared with the relational operators [000, [000, etc.

写一个名为 [00000279 的函数,以列表为形参,当列表按升序排列时返回 [000,否则返回 [0000。你可以假设(作为前置条件)列表里的元素能用关系运算符 [000、[000 等进行比较。

For example, [00000284 should return [000 and [00000286 should return [0000.

例如,[00000288 应返回 [000,[00000290 应返回 [0000。

Exercise 7

习题 7

Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called [00000292 that takes two strings and returns [000 if they are anagrams.

如果两个单词可以通过重排其中一个的字母拼出另一个,它们就是变位词(anagram)。写一个名为 [00000294 的函数,接受两个字符串,如果它们是变位词就返回 [000。

Exercise 8

习题 8

The (so-called) Birthday Paradox:

所谓的「生日悖论」:
  1. Write a function called [00000296 that takes a list and returns [000 if there is any element that appears more than once. It should not modify the original list.
  2. If there are 23 students in your class, what are the chances that two of you have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the [000002 function in the [00000 module.
  1. 写一个名为 [00000300 的函数,接受列表,若存在出现多于一次的元素就返回 [000。它不应修改原列表。
  2. 如果你的班上有 23 个学生,其中两人同一天生日的概率有多大?你可以生成 23 个生日的随机样本并检查是否有重复,从而估算这个概率。提示:可以用 [00000 模块的 [000003 函数生成随机生日。

You can read about this problem at [00000304, and you can download my solution from [00000305.

你可以在 [00000306 读到这个问题,也可以从 [00000307 下载我的解答。

Exercise 9

习题 9

Write a function called [00000308 that takes a list and returns a new list with only the unique elements from the original. Hint: they don’t have to be in the same order.

写一个名为 [00000309 的函数,接受列表,返回一个新列表,只包含原列表里不重复的元素。提示:不必保持原来的顺序。

Exercise 10

习题 10

Write a function that reads the file [00000310 and builds a list with one element per word. Write two versions of this function, one using the [00000 method and the other using the idiom [00000312. Which one takes longer to run? Why?

写一个函数,读取 [00000313 文件,构建一个列表,每个单词对应一个元素。写两个版本:一个用 [00000 方法,另一个用 [00000315 这个惯用法。哪个运行更慢?为什么?

Hint: use the [000 module to measure elapsed time. Solution: [00000317.

提示:用 [000 模块测量耗时。解答:[00000319。

Exercise 11

习题 11

To check whether a word is in the word list, you could use the [0 operator, but it would be slow because it searches through the words in order.

要检查某个单词是否在单词表中,可以用 [0 运算符,但那样会很慢,因为它按顺序逐个查找。

Because the words are in alphabetical order, we can speed things up with a bisection search (also known as binary search), which is similar to what you do when you look a word up in the dictionary. You start in the middle and check to see whether the word you are looking for comes before the word in the middle of the list. If so, then you search the first half of the list the same way. Otherwise you search the second half.

因为单词是按字母顺序排列的,我们可以用二分查找(bisection search,也叫 binary search)来加速,这类似于你在字典里查词。你从中间开始,看要找的词是否排在中点单词之前;如果是,就同样地在列表前半部分查找,否则就在后半部分查找。

Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will take about 17 steps to find the word or conclude that it’s not there.

无论哪种情况,你都把剩下的搜索范围砍掉一半。如果单词表有 113,809 个词,大约 17 步就能找到该词,或断定它不在表中。

Write a function called [00000 that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or [000 if it’s not.

写一个名为 [00000 的函数,接受已排序的列表和目标值,若值在列表中则返回其索引,否则返回 [000。

Or you could read the documentation of the [00000 module and use that! Solution: [00000327.

或者你也可以读一下 [00000 模块的文档,直接用它!解答:[00000329。

Exercise 12

习题 12

Two words are a “reverse pair” if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. Solution: [00000330.

如果两个单词互为反转,就是一对「反转对」(reverse pair)。写一个程序,找出单词表中所有的反转对。解答:[00000331。

Exercise 13

习题 13

Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled.” Solution: [00000332. Credit: This exercise is inspired by an example at [00000333.

如果两个单词「交错」(interlock)——各自取交替位置的字母能拼成一个新词——就算交错。例如,“shoe” 和 “cold” 交错拼成 “schooled.” 解答:[00000334。出处:本题灵感来自 [00000335 上的一个例子。
  1. Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs!
  2. Can you find any words that are three-way interlocked; that is, every third letter forms a word, starting from the first, second or third?
  1. 写一个程序,找出所有交错成对的单词。提示:别枚举所有配对!
  2. 你能找到三向交错的单词吗?也就是从第一个、第二个或第三个字母起,每隔两个字母组成一个词。