ホームページ >バックエンド開発 >Python チュートリアル >[译]Python チュートリアル#データ構造
この章では、以前に紹介したコンテンツの一部について詳しく説明し、また、いくつかの新しいコンテンツも紹介します。
リスト データ型にはさらに多くのメソッドがあります。リスト オブジェクトのすべてのメソッドは次のとおりです:
list.append(x)
新しい項目をリストの末尾に追加します (a[len(a):] = [x]
list.extend(iterable)
a[len(a):] = iterable
list.insert(i, x)
指定された位置に項目を挿入します。最初のパラメータは要素のインデックスで、新しい項目はこのインデックスの前に挿入されます。つまり a.insert(0, x)
会在列表最前面插入,a.insert(len(a), x)
等同于a.append(x)
です。
list.remove(x)
リストから値をx
的第一个项,若x
不存在,方法抛出异常(ValueError
Exception)
list.pop([i])
指定された位置にある項目をリストから削除して戻ります。インデックスが指定されていない場合、この位置に角括弧を記述する代わりに、a.pop()
移除并返回列表中最后一个项。(方法签名中包裹i
の角括弧はパラメータがオプションであることを示します。この表記法は Python ライブラリ リファレンスでよく使用されます)
list.clear()
リストからすべての項目を削除します (del a[:]
list.index(x[, start[, end]])
最初の値を x
的项的基于0的索引,如果x
不存在抛出ValueError
Exception として返します。
オプションの引数 start と end はスライス表記として解釈され、検索をリストの特定のサブリストに制限するために使用されます。返されるインデックスは、start パラメーターに対してではなく、完全なリスト インデックスに対して相対的なものになります。
list.count(x)
リスト内に x が出現する回数
list.sort(key=None, reverse=False)
リスト内のすべての項目を並べ替えます (パラメーターは並べ替えをカスタマイズするために使用されます。詳細については sorted()
を参照してください)
list.reverse()
リスト要素を逆順にします
list.copy()
a[:]
以下は list メソッドを示す例です:
insert, reverse
或者sort
的这样,只改变了列表但是没有返回值打印,它们返回默认的None
[1]など。これは、Python の可変データ構造に適用される設計原則です。
を使用して、スタックから最上位の要素をポップします。例: append()
方法添加元素到栈顶,使用不带参数的pop()
特別に設計された
両端の要素の追加と削除は非常に高速で、キューの実装に使用できます。例: collections.deque
正方形のリストを作成したい場合:
りー
という名前の変数を作成 (または書き換え) していることに注意してください。この変数はループ終了後もまだ存在します。副作用なしで二乗リストを作成するには、次のメソッドを使用します。 x
りー
は
句の評価結果に従います。たとえば、次のリスト内包表記では、2 つのリスト内の等しくない要素が結合されます。
for
子句,紧接零个或者多个for
子句或者if
子句的表达式再加上中括号,构成了列表推导式。其返回结果是一个新的列表,列表的元素是表达式中for
和if
りー
りー
注意上面两个代码段中for
和if
语句的顺序是相同的。
如果表达式是一个元组(如上所示的(x, y)),必须将其加上括号。
<code class="sourceCode python"><span class="op">>>></span> vec <span class="op">=</span> [<span class="op">-</span><span class="dv">4</span>, <span class="op">-</span><span class="dv">2</span>, <span class="dv">0</span>, <span class="dv">2</span>, <span class="dv">4</span>] <span class="op">>>></span> <span class="co"># create a new list with the values doubled</span> <span class="op">>>></span> [x<span class="op">*</span><span class="dv">2</span> <span class="cf">for</span> x <span class="op">in</span> vec] [<span class="op">-</span><span class="dv">8</span>, <span class="op">-</span><span class="dv">4</span>, <span class="dv">0</span>, <span class="dv">4</span>, <span class="dv">8</span>] <span class="op">>>></span> <span class="co"># filter the list to exclude negative numbers</span> <span class="op">>>></span> [x <span class="cf">for</span> x <span class="op">in</span> vec <span class="cf">if</span> x <span class="op">>=</span> <span class="dv">0</span>] [<span class="dv">0</span>, <span class="dv">2</span>, <span class="dv">4</span>] <span class="op">>>></span> <span class="co"># apply a function to all the elements</span> <span class="op">>>></span> [<span class="bu">abs</span>(x) <span class="cf">for</span> x <span class="op">in</span> vec] [<span class="dv">4</span>, <span class="dv">2</span>, <span class="dv">0</span>, <span class="dv">2</span>, <span class="dv">4</span>] <span class="op">>>></span> <span class="co"># call a method on each element</span> <span class="op">>>></span> freshfruit <span class="op">=</span> [<span class="st">' banana'</span>, <span class="st">' loganberry '</span>, <span class="st">'passion fruit '</span>] <span class="op">>>></span> [weapon.strip() <span class="cf">for</span> weapon <span class="op">in</span> freshfruit] [<span class="st">'banana'</span>, <span class="st">'loganberry'</span>, <span class="st">'passion fruit'</span>] <span class="op">>>></span> <span class="co"># create a list of 2-tuples like (number, square)</span> <span class="op">>>></span> [(x, x<span class="op">**</span><span class="dv">2</span>) <span class="cf">for</span> x <span class="op">in</span> <span class="bu">range</span>(<span class="dv">6</span>)] [(<span class="dv">0</span>, <span class="dv">0</span>), (<span class="dv">1</span>, <span class="dv">1</span>), (<span class="dv">2</span>, <span class="dv">4</span>), (<span class="dv">3</span>, <span class="dv">9</span>), (<span class="dv">4</span>, <span class="dv">16</span>), (<span class="dv">5</span>, <span class="dv">25</span>)] <span class="op">>>></span> <span class="co"># the tuple must be parenthesized, otherwise an error is raised</span> <span class="op">>>></span> [x, x<span class="op">**</span><span class="dv">2</span> <span class="cf">for</span> x <span class="op">in</span> <span class="bu">range</span>(<span class="dv">6</span>)] File <span class="st">"<stdin>"</span>, line <span class="dv">1</span>, <span class="op">in</span> <span class="op"><</span>module<span class="op">></span> [x, x<span class="op">**</span><span class="dv">2</span> <span class="cf">for</span> x <span class="op">in</span> <span class="bu">range</span>(<span class="dv">6</span>)] <span class="op">^</span> <span class="pp">SyntaxError</span>: invalid syntax <span class="op">>>></span> <span class="co"># flatten a list using a listcomp with two 'for'</span> <span class="op">>>></span> vec <span class="op">=</span> [[<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>], [<span class="dv">4</span>,<span class="dv">5</span>,<span class="dv">6</span>], [<span class="dv">7</span>,<span class="dv">8</span>,<span class="dv">9</span>]] <span class="op">>>></span> [num <span class="cf">for</span> elem <span class="op">in</span> vec <span class="cf">for</span> num <span class="op">in</span> elem] [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>, <span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>]</code>
列表推导式可以包含复杂的表达式甚至嵌套函数:
<code class="sourceCode python"><span class="op">>>></span> <span class="im">from</span> math <span class="im">import</span> pi <span class="op">>>></span> [<span class="bu">str</span>(<span class="bu">round</span>(pi, i)) <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">1</span>, <span class="dv">6</span>)] [<span class="st">'3.1'</span>, <span class="st">'3.14'</span>, <span class="st">'3.142'</span>, <span class="st">'3.1416'</span>, <span class="st">'3.14159'</span>]</code>
列表推导式开头的表达式可以是任意表达式,包括另一个列表推导式。
考虑以下示例,一个包含3个长度为4的列表的列表实现了3x4的矩阵:
<code class="sourceCode python">matrix <span class="op">=</span> [ [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>], [<span class="dv">5</span>, <span class="dv">6</span>, <span class="dv">7</span>, <span class="dv">8</span>], [<span class="dv">9</span>, <span class="dv">10</span>, <span class="dv">11</span>, <span class="dv">12</span>], ]</code>
以下列表推导式反转行列:
<code class="sourceCode python"><span class="op">>>></span> [[row[i] <span class="cf">for</span> row <span class="op">in</span> matrix] <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">4</span>)] [[<span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">9</span>], [<span class="dv">2</span>, <span class="dv">6</span>, <span class="dv">10</span>], [<span class="dv">3</span>, <span class="dv">7</span>, <span class="dv">11</span>], [<span class="dv">4</span>, <span class="dv">8</span>, <span class="dv">12</span>]]</code>
前面的章节提到,嵌套的列表推导式是在其后跟随的for
的上下文中求值的,因此这个示例等同于:
<code class="sourceCode python"><span class="op">>>></span> transposed <span class="op">=</span> [] <span class="op">>>></span> <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">4</span>): ... transposed.append([row[i] <span class="cf">for</span> row <span class="op">in</span> matrix]) ... <span class="op">>>></span> transposed [[<span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">9</span>], [<span class="dv">2</span>, <span class="dv">6</span>, <span class="dv">10</span>], [<span class="dv">3</span>, <span class="dv">7</span>, <span class="dv">11</span>], [<span class="dv">4</span>, <span class="dv">8</span>, <span class="dv">12</span>]]</code>
依次等同于:
<code class="sourceCode python"><span class="op">>>></span> transposed <span class="op">=</span> [] <span class="op">>>></span> <span class="cf">for</span> i <span class="op">in</span> <span class="bu">range</span>(<span class="dv">4</span>): ... <span class="co"># the following 3 lines implement the nested listcomp</span> ... transposed_row <span class="op">=</span> [] ... <span class="cf">for</span> row <span class="op">in</span> matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) <span class="op">>>></span> transposed [[<span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">9</span>], [<span class="dv">2</span>, <span class="dv">6</span>, <span class="dv">10</span>], [<span class="dv">3</span>, <span class="dv">7</span>, <span class="dv">11</span>], [<span class="dv">4</span>, <span class="dv">8</span>, <span class="dv">12</span>]]</code>
在实践中,应该选择built-in函数来复合流程语句。在以上的用例中zip()
函数更有用:
<code class="sourceCode python"><span class="op">>>></span> <span class="bu">list</span>(<span class="bu">zip</span>(<span class="op">*</span>matrix)) [(<span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">9</span>), (<span class="dv">2</span>, <span class="dv">6</span>, <span class="dv">10</span>), (<span class="dv">3</span>, <span class="dv">7</span>, <span class="dv">11</span>), (<span class="dv">4</span>, <span class="dv">8</span>, <span class="dv">12</span>)]</code>
参见 Unpacking Argument Lists了解关于上面*
使用的更多详细信息。
在提供列表索引而不是值的情况下,有一种方法可以移除列表中的元素:del
语句。这种方式与返回值的pop()
方法不同。del
语句也可以用来移除部分列表或者清除整个列表(之前使用将空的列表赋值给列表片段的方式实现)。示例:
<code class="sourceCode python"><span class="op">>>></span> a <span class="op">=</span> [<span class="op">-</span><span class="dv">1</span>, <span class="dv">1</span>, <span class="fl">66.25</span>, <span class="dv">333</span>, <span class="dv">333</span>, <span class="fl">1234.5</span>] <span class="op">>>></span> <span class="kw">del</span> a[<span class="dv">0</span>] <span class="op">>>></span> a [<span class="dv">1</span>, <span class="fl">66.25</span>, <span class="dv">333</span>, <span class="dv">333</span>, <span class="fl">1234.5</span>] <span class="op">>>></span> <span class="kw">del</span> a[<span class="dv">2</span>:<span class="dv">4</span>] <span class="op">>>></span> a [<span class="dv">1</span>, <span class="fl">66.25</span>, <span class="fl">1234.5</span>] <span class="op">>>></span> <span class="kw">del</span> a[:] <span class="op">>>></span> a []</code>
del
也可以用来删除整个变量:
<code class="sourceCode python"><span class="op">>>></span> <span class="kw">del</span> a</code>
此后引用名字a
会抛出异常(至少在其他值赋值给名字a
之前)。接下来会有更多del
的使用
列表和字符串有很多常用属性,比如索引和切片操作。它们是序列数据类型(参见 Sequence Types - list, tuple, range)的两种。Python是一种不断进化的语言,其他的序列类型也可以加入。元组是另一种标准的序列数据类型。
元组包含若干由逗号分隔的值,示例:
<code class="sourceCode python"><span class="op">>>></span> t <span class="op">=</span> <span class="dv">12345</span>, <span class="dv">54321</span>, <span class="st">'hello!'</span> <span class="op">>>></span> t[<span class="dv">0</span>] <span class="dv">12345</span> <span class="op">>>></span> t (<span class="dv">12345</span>, <span class="dv">54321</span>, <span class="st">'hello!'</span>) <span class="op">>>></span> <span class="co"># Tuples may be nested:</span> ... u <span class="op">=</span> t, (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>) <span class="op">>>></span> u ((<span class="dv">12345</span>, <span class="dv">54321</span>, <span class="st">'hello!'</span>), (<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>, <span class="dv">5</span>)) <span class="op">>>></span> <span class="co"># Tuples are immutable:</span> ... t[<span class="dv">0</span>] <span class="op">=</span> <span class="dv">88888</span> Traceback (most recent call last): File <span class="st">"<stdin>"</span>, line <span class="dv">1</span>, <span class="op">in</span> <span class="op"><</span>module<span class="op">></span> <span class="pp">TypeError</span>: <span class="st">'tuple'</span> <span class="bu">object</span> does <span class="op">not</span> support item assignment <span class="op">>>></span> <span class="co"># but they can contain mutable objects:</span> ... v <span class="op">=</span> ([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>]) <span class="op">>>></span> v ([<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>], [<span class="dv">3</span>, <span class="dv">2</span>, <span class="dv">1</span>])</code>
可见,输出的元组总是放在圆括号中,以便于嵌套的元组可以被正确解析;虽然圆括号总是必须的(如果元组是其他更大表达式的一部分),但是在输入元组的时候可以选择使用圆括号。不能对元组的单个项赋值,但是可以创建包含如列表的可变对象的元组。
虽然元组和列表有些相似,但是他们通常以不同的目的,用于不同的场景。元组是不可变的,通常包含不同类型的元素,可以通过拆包操作(参见后续章节)或者索引(或者当元组是命名元组时,甚至可以通过属性来访问)来访问。列表是可变的,通常其元素也是不同类型的,可以通过对列表的迭代访问元素。
构建包含零个或者1个项的元组比较特殊:一种额外的奇怪语法可以适用于这种情况。空元组由一对空的圆括号创建;一个元素的元组由一个跟着逗号的值创建(在圆括号中放入单个值是不够的。译注:这种情况:(1)表示整数而不是元组,使用(1, )表示元组也是可行的)。丑陋但是有效。示例:
<code class="sourceCode python"><span class="op">>>></span> empty <span class="op">=</span> () <span class="op">>>></span> singleton <span class="op">=</span> <span class="st">'hello'</span>, <span class="co"># <-- note trailing comma</span> <span class="op">>>></span> <span class="bu">len</span>(empty) <span class="dv">0</span> <span class="op">>>></span> <span class="bu">len</span>(singleton) <span class="dv">1</span> <span class="op">>>></span> singleton (<span class="st">'hello'</span>,)</code>
语句t = 12345, 54321, 'hello!'
是封装元组的一个示例:值12345, 54321
和hello!
被封装到了一个元组中。逆向操作也是可行的:
<code class="sourceCode python"><span class="op">>>></span> x, y, z <span class="op">=</span> t</code>
非常恰当地称之为序列解包,适用于任何在等号右边的序列(译注:等号右操作数)。序列解包要求等号左边待赋值的变量数量与序列包含元素数目相同。注意多重赋值只是封装元组和序列解包的结合(译注:多重赋值:i, j = 1, 2
)
Python也包含实现了集合的数据类型。集合是无序不重复的元素集。基本功能包括成员关系测试和重复实体消除。集合对象也支持并集,交集,差集以及对称差集等数学操作。
可以使用花括号和set()
函数创建集合。谨记:创建空集合必须使用set
函数,不能使用{}
,后者用于创建空字典。
以下是简单示范:
<code class="sourceCode python"><span class="op">>>></span> basket <span class="op">=</span> {<span class="st">'apple'</span>, <span class="st">'orange'</span>, <span class="st">'apple'</span>, <span class="st">'pear'</span>, <span class="st">'orange'</span>, <span class="st">'banana'</span>} <span class="op">>>></span> <span class="bu">print</span>(basket) <span class="co"># show that duplicates have been removed</span> {<span class="st">'orange'</span>, <span class="st">'banana'</span>, <span class="st">'pear'</span>, <span class="st">'apple'</span>} <span class="op">>>></span> <span class="st">'orange'</span> <span class="op">in</span> basket <span class="co"># fast membership testing</span> <span class="va">True</span> <span class="op">>>></span> <span class="st">'crabgrass'</span> <span class="op">in</span> basket <span class="va">False</span> <span class="op">>>></span> <span class="co"># Demonstrate set operations on unique letters from two words</span> ... <span class="op">>>></span> a <span class="op">=</span> <span class="bu">set</span>(<span class="st">'abracadabra'</span>) <span class="op">>>></span> b <span class="op">=</span> <span class="bu">set</span>(<span class="st">'alacazam'</span>) <span class="op">>>></span> a <span class="co"># unique letters in a</span> {<span class="st">'a'</span>, <span class="st">'r'</span>, <span class="st">'b'</span>, <span class="st">'c'</span>, <span class="st">'d'</span>} <span class="op">>>></span> a <span class="op">-</span> b <span class="co"># letters in a but not in b</span> {<span class="st">'r'</span>, <span class="st">'d'</span>, <span class="st">'b'</span>} <span class="op">>>></span> a <span class="op">|</span> b <span class="co"># letters in a or b or both</span> {<span class="st">'a'</span>, <span class="st">'c'</span>, <span class="st">'r'</span>, <span class="st">'d'</span>, <span class="st">'b'</span>, <span class="st">'m'</span>, <span class="st">'z'</span>, <span class="st">'l'</span>} <span class="op">>>></span> a <span class="op">&</span> b <span class="co"># letters in both a and b</span> {<span class="st">'a'</span>, <span class="st">'c'</span>} <span class="op">>>></span> a <span class="op">^</span> b <span class="co"># letters in a or b but not both</span> {<span class="st">'r'</span>, <span class="st">'d'</span>, <span class="st">'b'</span>, <span class="st">'m'</span>, <span class="st">'z'</span>, <span class="st">'l'</span>}</code>
与列表推导式相同,Python也支持集合推导式:
<code class="sourceCode python"><span class="op">>>></span> a <span class="op">=</span> {x <span class="cf">for</span> x <span class="op">in</span> <span class="st">'abracadabra'</span> <span class="cf">if</span> x <span class="op">not</span> <span class="op">in</span> <span class="st">'abc'</span>} <span class="op">>>></span> a {<span class="st">'r'</span>, <span class="st">'d'</span>}</code>
另一个内嵌入Python中的数据结构是字典(参见 Mapping Types - dict)。字典在其他一些语言中被称为“联合存储”或者“联合数组”。与序列不同,序列以一系列数字作索引,字典以键作索引,键可以是任何不可变类型;通常使用字符串和数字作为键。只包含字符串,数字或者其他元组的元组也可以作为键;直接或者间接包含可变对象的元组不能作为键。因为列表可以使用索引赋值,切片赋值或者append()
以及extend()
等方法改变自身,所以列表不能作为键。
最好的理解字典的方式是将其认为是键值对的无序集合,同一集合中键唯一。一对花括号创建空字典:{}
。在花括号中放置由逗号分隔键值对列表可以为字典添加初始键值对;这也是字典输出的格式。
字典提供的主要操作是:使用键存储值以及取值。可以使用del
删除一个键值对。如果使用已经存在的键来存储值,那么与键关联的旧值会被重写。使用不存在的键来取值会抛出异常。
在字典上执行list(d.keys())
返回字典所有键的无序列表(使用sorted(d.keys())
使其有序)[2]。使用关键字in
检查键在字典中是否存在。
以下是使用字典的示例:
<code class="sourceCode python"><span class="op">>>></span> tel <span class="op">=</span> {<span class="st">'jack'</span>: <span class="dv">4098</span>, <span class="st">'sape'</span>: <span class="dv">4139</span>} <span class="op">>>></span> tel[<span class="st">'guido'</span>] <span class="op">=</span> <span class="dv">4127</span> <span class="op">>>></span> tel {<span class="st">'sape'</span>: <span class="dv">4139</span>, <span class="st">'guido'</span>: <span class="dv">4127</span>, <span class="st">'jack'</span>: <span class="dv">4098</span>} <span class="op">>>></span> tel[<span class="st">'jack'</span>] <span class="dv">4098</span> <span class="op">>>></span> <span class="kw">del</span> tel[<span class="st">'sape'</span>] <span class="op">>>></span> tel[<span class="st">'irv'</span>] <span class="op">=</span> <span class="dv">4127</span> <span class="op">>>></span> tel {<span class="st">'guido'</span>: <span class="dv">4127</span>, <span class="st">'irv'</span>: <span class="dv">4127</span>, <span class="st">'jack'</span>: <span class="dv">4098</span>} <span class="op">>>></span> <span class="bu">list</span>(tel.keys()) [<span class="st">'irv'</span>, <span class="st">'guido'</span>, <span class="st">'jack'</span>] <span class="op">>>></span> <span class="bu">sorted</span>(tel.keys()) [<span class="st">'guido'</span>, <span class="st">'irv'</span>, <span class="st">'jack'</span>] <span class="op">>>></span> <span class="st">'guido'</span> <span class="op">in</span> tel <span class="va">True</span> <span class="op">>>></span> <span class="st">'jack'</span> <span class="op">not</span> <span class="op">in</span> tel <span class="va">False</span></code>
dict()
构造器直接使用键值对序列构造字典:
<code class="sourceCode python"><span class="op">>>></span> <span class="bu">dict</span>([(<span class="st">'sape'</span>, <span class="dv">4139</span>), (<span class="st">'guido'</span>, <span class="dv">4127</span>), (<span class="st">'jack'</span>, <span class="dv">4098</span>)]) {<span class="st">'sape'</span>: <span class="dv">4139</span>, <span class="st">'jack'</span>: <span class="dv">4098</span>, <span class="st">'guido'</span>: <span class="dv">4127</span>}</code>
此外,字典推导式可以从任意键值表达式中创建字典:
<code class="sourceCode python"><span class="op">>>></span> {x: x<span class="op">**</span><span class="dv">2</span> <span class="cf">for</span> x <span class="op">in</span> (<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">6</span>)} {<span class="dv">2</span>: <span class="dv">4</span>, <span class="dv">4</span>: <span class="dv">16</span>, <span class="dv">6</span>: <span class="dv">36</span>}</code>
当键是简单的字符串时,可以使用关键字参数来指定键值对:
<code class="sourceCode python"><span class="op">>>></span> <span class="bu">dict</span>(sape<span class="op">=</span><span class="dv">4139</span>, guido<span class="op">=</span><span class="dv">4127</span>, jack<span class="op">=</span><span class="dv">4098</span>) {<span class="st">'sape'</span>: <span class="dv">4139</span>, <span class="st">'jack'</span>: <span class="dv">4098</span>, <span class="st">'guido'</span>: <span class="dv">4127</span>}</code>
遍历字典时,使用items()
方法可以同时检索键及其对应的值。
<code class="sourceCode python"><span class="op">>>></span> knights <span class="op">=</span> {<span class="st">'gallahad'</span>: <span class="st">'the pure'</span>, <span class="st">'robin'</span>: <span class="st">'the brave'</span>} <span class="op">>>></span> <span class="cf">for</span> k, v <span class="op">in</span> knights.items(): ... <span class="bu">print</span>(k, v) ... gallahad the pure robin the brave</code>
遍历序列时,使用enumerate()
函数可以同时检索位置索引及其对应的值:
<code class="sourceCode python"><span class="op">>>></span> <span class="cf">for</span> i, v <span class="op">in</span> <span class="bu">enumerate</span>([<span class="st">'tic'</span>, <span class="st">'tac'</span>, <span class="st">'toe'</span>]): ... <span class="bu">print</span>(i, v) ... <span class="dv">0</span> tic <span class="dv">1</span> tac <span class="dv">2</span> toe</code>
同时遍历两个或者更多序列时,使用zip()
函数可以将元素组成对:
<code class="sourceCode python"><span class="op">>>></span> questions <span class="op">=</span> [<span class="st">'name'</span>, <span class="st">'quest'</span>, <span class="st">'favorite color'</span>] <span class="op">>>></span> answers <span class="op">=</span> [<span class="st">'lancelot'</span>, <span class="st">'the holy grail'</span>, <span class="st">'blue'</span>] <span class="op">>>></span> <span class="cf">for</span> q, a <span class="op">in</span> <span class="bu">zip</span>(questions, answers): ... <span class="bu">print</span>(<span class="st">'What is your </span><span class="sc">{0}</span><span class="st">? It is </span><span class="sc">{1}</span><span class="st">.'</span>.<span class="bu">format</span>(q, a)) ... What <span class="op">is</span> your name? It <span class="op">is</span> lancelot. What <span class="op">is</span> your quest? It <span class="op">is</span> the holy grail. What <span class="op">is</span> your favorite color? It <span class="op">is</span> blue.</code>
需要逆序遍历序列时,首先指定一个正向的序列,然后调用reversed()
函数:
<code class="sourceCode python"><span class="op">>>></span> <span class="cf">for</span> i <span class="op">in</span> <span class="bu">reversed</span>(<span class="bu">range</span>(<span class="dv">1</span>, <span class="dv">10</span>, <span class="dv">2</span>)): ... <span class="bu">print</span>(i) ... <span class="dv">9</span> <span class="dv">7</span> <span class="dv">5</span> <span class="dv">3</span> <span class="dv">1</span></code>
需要以特定顺序遍历序列时,使用sorted()
函数返回新的有序序列,原序列不会改动:
<code class="sourceCode python"><span class="op">>>></span> basket <span class="op">=</span> [<span class="st">'apple'</span>, <span class="st">'orange'</span>, <span class="st">'apple'</span>, <span class="st">'pear'</span>, <span class="st">'orange'</span>, <span class="st">'banana'</span>] <span class="op">>>></span> <span class="cf">for</span> f <span class="op">in</span> <span class="bu">sorted</span>(<span class="bu">set</span>(basket)): ... <span class="bu">print</span>(f) ... apple banana orange pear</code>
有时需要在遍历序列的同时修改序列,创建新的替代序列更加简单并且安全:
<code class="sourceCode python"><span class="op">>>></span> <span class="im">import</span> math <span class="op">>>></span> raw_data <span class="op">=</span> [<span class="fl">56.2</span>, <span class="bu">float</span>(<span class="st">'NaN'</span>), <span class="fl">51.7</span>, <span class="fl">55.3</span>, <span class="fl">52.5</span>, <span class="bu">float</span>(<span class="st">'NaN'</span>), <span class="fl">47.8</span>] <span class="op">>>></span> filtered_data <span class="op">=</span> [] <span class="op">>>></span> <span class="cf">for</span> value <span class="op">in</span> raw_data: ... <span class="cf">if</span> <span class="op">not</span> math.isnan(value): ... filtered_data.append(value) ... <span class="op">>>></span> filtered_data [<span class="fl">56.2</span>, <span class="fl">51.7</span>, <span class="fl">55.3</span>, <span class="fl">52.5</span>, <span class="fl">47.8</span>]</code>
while
和if
语句中使用的条件可以包含任意操作符,不仅仅是比较运算符。
比较运算符in
和not in
检查指定值在序列中是否存在(不存在)。操作符is
和is not
比较两个对象是否真正相同(内存地址比较);这两个操作符只对像列表那样的可变对象重要。所有的比较运算符拥有相同的优先级,并且都低于数字运算符。
比较运算符可以链接起来。例如a ebee1f8a764ba39dad659ec343d8da37
比较不同类型的对象是合法的。例如,混合数字类型之间的比较是根据其数字上的值,0等于0.0。否则,解释器会抛出TypeException
异常,而不是随意提供结果
[1] 其他语言可能返回改变后的对象,从而允许方法链接,如:d->insert("a")>remove("b")->sort();
[2] 调用d.keys()
返回一个dictionary view对象。从而支持如成员关系测试和迭代之类的操作,但是其内容并不是独立于原始字典的,只是一个视图
以上が[译]Python チュートリアル#データ構造の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。