python中字典列表元组
Lists and tuples are arguably Python’s most versatile, useful data types. You will find them in virtually every nontrivial Python program.
列表和元组可以说是Python最通用,最有用的数据类型。 您几乎可以在每个平凡的Python程序中找到它们。
Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.
这是在本教程中将学到的内容:您将介绍列表和元组的重要特征。 您将学习如何定义它们以及如何操作它们。 完成后,您应该对何时以及如何在Python程序中使用这些对象类型有很好的了解。
Python列表 (Python Lists)
In short, a list is a collection of arbitrary objects, somewhat akin to an array in many other programming languages but more flexible. Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ([]
), as shown below:
简而言之,列表是任意对象的集合,类似于许多其他编程语言中的数组,但更为灵活。 清单是在Python中定义的,方法是将用逗号分隔的对象序列括在方括号( []
)中,如下所示:
>> a = ['foo', 'bar', 'baz', 'qux']
>> a = ['foo', 'bar', 'baz', 'qux']
>>> >>> printprint (( aa )
)
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
>>> >>> a
a
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
The important characteristics of Python lists are as follows:
Python列表的重要特征如下:
- Lists are ordered.
- Lists can contain any arbitrary objects.
- List elements can be accessed by index.
- Lists can be nested to arbitrary depth.
- Lists are mutable.
- Lists are dynamic.
- 列表是有序的。
- 列表可以包含任何任意对象。
- 列表元素可以通过索引访问。
- 列表可以嵌套到任意深度。
- 列表是可变的。
- 列表是动态的。
Each of these features is examined in more detail below.
这些功能中的每一个都将在下面更详细地研究。
列表已排序 (Lists Are Ordered)
A list is not merely a collection of objects. It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. (You will see a Python data type that is not ordered in the next tutorial on dictionaries.)
列表不仅是对象的集合。 它是对象的有序集合。 定义列表时指定元素的顺序是该列表的固有特性,并在该列表的生命周期内保持不变。 (您将看到在下一本关于字典的教程中未排序的Python数据类型。)
Lists that have the same elements in a different order are not the same:
具有相同元素但顺序不同的列表是不同的:
列表可以包含任意对象 (Lists Can Contain Arbitrary Objects)
A list can contain any assortment of objects. The elements of a list can all be the same type:
列表可以包含任何种类的对象。 列表的元素都可以是同一类型:
>>> >>> a a = = [[ 22 , , 44 , , 66 , , 88 ]
]
>>> >>> a
a
[2, 4, 6, 8]
[2, 4, 6, 8]
Or the elements can be of varying types:
或者元素可以是不同的类型:
Lists can even contain complex objects, like functions, classes, and modules, which you will learn about in upcoming tutorials:
列表甚至可以包含复杂的对象,例如函数,类和模块,您将在接下来的教程中了解这些对象:
>>> >>> int
int
<class 'int'>
<class 'int'>
>>> >>> len
len
<built-in function len>
<built-in function len>
>>> >>> def def foofoo ():
():
... ... pass
pass
...
...
>>> >>> foo
foo
<function foo at 0x035B9030>
<function foo at 0x035B9030>
>>> >>> import import math
math
>>> >>> math
math
<module 'math' (built-in)>
<module 'math' (built-in)>
>>> >>> a a = = [[ intint , , lenlen , , foofoo , , mathmath ]
]
>>> >>> a
a
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
<module 'math' (built-in)>]
<module 'math' (built-in)>]
A list can contain any number of objects, from zero to as many as your computer’s memory will allow:
列表可以包含任意数量的对象,从零到您的计算机内存允许的数量:
(A list with a single object is sometimes referred to as a singleton list.)
(具有单个对象的列表有时称为单例列表。)
List objects needn’t be unique. A given object can appear in a list multiple times:
列表对象不必唯一。 给定的对象可以多次出现在列表中:
>>> >>> a a = = [[ 'bark''bark' , , 'meow''meow' , , 'woof''woof' , , 'bark''bark' , , 'cheep''cheep' , , 'bark''bark' ]
]
>>> >>> a
a
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
列表元素可以通过索引访问 (List Elements Can Be Accessed by Index)
Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings.
列表中的各个元素可以使用方括号中的索引进行访问。 这完全类似于访问字符串中的单个字符。 列表索引与字符串一样,都是从零开始的。
Consider the following list:
考虑以下列表:
The indices for the elements in a
are shown below:
a
中元素的索引如下所示:
![Diagram of a Python list](https://i-blog.csdnimg.cn/blog_migrate/7d5462002a2b92fbabdc7c96d076eff8.png)
Here is Python code to access some elements of a
:
下面是Python代码访问的一些元素a
:
>>> >>> aa [[ 00 ]
]
'foo'
'foo'
>>> >>> aa [[ 22 ]
]
'baz'
'baz'
>>> >>> aa [[ 55 ]
]
'corge'
'corge'
Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:
实际上,有关字符串索引的所有内容对于列表而言都类似。 例如,负列表索引从列表的末尾开始计数:
![Python列表图](https://i-blog.csdnimg.cn/blog_migrate/831021ecc9b22fcdb1be8af3f91e9473.png)
Slicing also works. If a
is a list, the expression a[m:n]
returns the portion of a
from index m
to, but not including, index n
:
切片也可以。 如果a
是一个列表,则表达式a[m:n]
返回a
从索引m
到但不包括索引n
:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> aa [[ 22 :: 55 ]
]
['baz', 'qux', 'quux']
['baz', 'qux', 'quux']
Other features of string slicing work analogously for list slicing as well:
字符串切片的其他功能也类似地用于列表切片:
-
Both positive and negative indices can be specified:
-
Omitting the first index starts the slice at the beginning of the list, and omitting the second index extends the slice to the end of the list:
>>> print(a[:4], a[0:4]) ['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux'] >>> print(a[2:], a[2:len(a)]) ['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge'] >>> a[:4] + a[4:] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[:4] + a[4:] == a True
-
You can specify a stride—either positive or negative:
-
The syntax for reversing a list works the same way it does for strings:
>>> a[::-1] ['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
-
The
[:]
syntax works for lists. However, there is an important difference between how this operation works with a list and how it works with a string.If
s
is a string,s[:]
returns a reference to the same object:Conversely, if
a
is a list,a[:]
returns a new object that is a copy ofa
:>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[:] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[:] is a False
-
正负索引均可指定:
-
省略第一个索引会在列表的开头开始切片,而省略第二个索引会将切片扩展到列表的末尾:
>>> print ( a [: 4 ], a [ 0 : 4 ]) ['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux'] >>> print ( a [ 2 :], a [ 2 : len ( a )]) ['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge'] >>> a [: 4 ] + a [ 4 :] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a [: 4 ] + a [ 4 :] == a True
-
您可以指定一个步幅(正数或负数):
-
反转列表的语法与处理字符串的方法相同:
>>> a [:: - 1 ] ['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
-
[:]
语法适用于列表。 但是,此操作如何与列表一起使用以及如何与字符串一起使用之间存在重要区别。如果
s
是字符串,则s[:]
返回对同一对象的引用:相反,如果
a
是一个列表,a[:]
返回一个新对象的副本a
:>>> a = [ 'foo' , 'bar' , 'baz' , 'qux' , 'quux' , 'corge' ] >>> a [:] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a [:] is a False
Several Python operators and built-in functions can also be used with lists in ways that are analogous to strings:
几个Python运算符和内置函数也可以类似于字符串的方式与列表一起使用:
-
The
in
andnot in
operators: -
The concatenation (
+
) and replication (*
) operators:>>> a ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a + ['grault', 'garply'] ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply'] >>> a * 2 ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
-
The
len()
,min()
, andmax()
functions:
-
in
和not in
运算符:>>> a ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> 'qux' in a True >>> 'thud' not in a True
-
串联(
+
)和复制(*
)运算符: -
len()
,min()
和max()
函数:>>> a ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> len ( a ) 6 >>> min ( a ) 'bar' >>> max ( a ) 'qux'
It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called an iterable, which you will encounter in more detail in the upcoming tutorial on definite iteration.
字符串和列表的行为如此相似并非偶然。 它们都是更常见的对象类型(称为Iterable)的特例,您将在即将到来的有关确定迭代的教程中更详细地介绍这些对象。
By the way, in each example above, the list is always assigned to a variable before an operation is performed on it. But you can operate on a list literal as well:
顺便说一下,在上面的每个示例中,始终在对变量执行操作之前将列表分配给变量。 但是您也可以对列表文字进行操作:
For that matter, you can do likewise with a string literal:
为此,您也可以对字符串文字进行处理:
>>> >>> 'If Comrade Napoleon says it, it must be right.''If Comrade Napoleon says it, it must be right.' [::[:: -- 11 ]
]
'.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
'.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
列表可以嵌套 (Lists Can Be Nested)
You have seen that an element in a list can be any sort of object. That includes another list. A list can contain sublists, which in turn can contain sublists themselves, and so on to arbitrary depth.
您已经看到列表中的元素可以是任何种类的对象。 其中包括另一个列表。 列表可以包含子列表,而子列表又可以包含子列表本身,依此类推可以任意深度。
Consider this (admittedly contrived) example:
考虑以下(公认的)示例:
The object structure that x
references is diagrammed below:
x
引用的对象结构如下图所示:
![Nested lists diagram](https://i-blog.csdnimg.cn/blog_migrate/d6504c9d7130aa826f056b08bef14280.png)
x[0]
, x[2]
, and x[4]
are strings, each one character long:
x[0]
, x[2]
和x[4]
是字符串,每个字符长:
>>> >>> printprint (( xx [[ 00 ], ], xx [[ 22 ], ], xx [[ 44 ])
])
a g j
a g j
But x[1]
and x[3]
are sublists:
但是x[1]
和x[3]
是子列表:
To access the items in a sublist, simply append an additional index:
要访问子列表中的项目,只需附加一个附加索引:
>>> >>> xx [[ 11 ]
]
['bb', ['ccc', 'ddd'], 'ee', 'ff']
['bb', ['ccc', 'ddd'], 'ee', 'ff']
>>> >>> xx [[ 11 ][][ 00 ]
]
'bb'
'bb'
>>> >>> xx [[ 11 ][][ 11 ]
]
['ccc', 'ddd']
['ccc', 'ddd']
>>> >>> xx [[ 11 ][][ 22 ]
]
'ee'
'ee'
>>> >>> xx [[ 11 ][][ 33 ]
]
'ff'
'ff'
>>> >>> xx [[ 33 ]
]
['hh', 'ii']
['hh', 'ii']
>>> >>> printprint (( xx [[ 33 ][][ 00 ], ], xx [[ 33 ][][ 11 ])
])
hh ii
hh ii
x[1][1]
is yet another sublist, so adding one more index accesses its elements:
x[1][1]
是另一个子列表,因此再添加一个索引即可访问其元素:
There is no limit, short of the extent of your computer’s memory, to the depth or complexity with which lists can be nested in this way.
除了计算机内存的大小外,列表可以以这种方式嵌套的深度或复杂性没有限制。
All the usual syntax regarding indices and slicing applies to sublists as well:
关于索引和切片的所有常规语法也适用于子列表:
>>> >>> xx [[ 11 ][][ 11 ][][ -- 11 ]
]
'ddd'
'ddd'
>>> >>> xx [[ 11 ][][ 11 :: 33 ]
]
[['ccc', 'ddd'], 'ee']
[['ccc', 'ddd'], 'ee']
>>> >>> xx [[ 33 ][::][:: -- 11 ]
]
['ii', 'hh']
['ii', 'hh']
However, be aware that operators and functions apply to only the list at the level you specify and are not recursive. Consider what happens when you query the length of x
using len()
:
但是,请注意,运算符和函数仅适用于您指定级别的列表,并且不是递归的。 考虑当您使用len()
查询x
的长度时会发生什么:
x
has only five elements—three strings and two sublists. The individual elements in the sublists don’t count toward x
’s length.
x
只有五个元素-三个字符串和两个子列表。 子列表中的各个元素不计入x
的长度。
You’d encounter a similar situation when using the in
operator:
使用in
运算符时,您会遇到类似的情况:
>>> >>> 'ddd' 'ddd' in in x
x
False
False
>>> >>> 'ddd' 'ddd' in in xx [[ 11 ]
]
False
False
>>> >>> 'ddd' 'ddd' in in xx [[ 11 ][][ 11 ]
]
True
True
'ddd'
is not one of the elements in x
or x[1]
. It is only directly an element in the sublist x[1][1]
. An individual element in a sublist does not count as an element of the parent list(s).
'ddd'
不是x
或x[1]
中的元素之一。 它仅是子列表x[1][1]
中的一个直接元素。 子列表中的单个元素不算作父列表的元素。
列表是可变的 (Lists Are Mutable)
Most of the data types you have encountered so far have been atomic types. Integer or float objects, for example, are primitive units that can’t be further broken down. These types are immutable, meaning that they can’t be changed once they have been assigned. It doesn’t make much sense to think of changing the value of an integer. If you want a different integer, you just assign a different one.
到目前为止,您遇到的大多数数据类型都是原子类型。 例如,整数或浮点对象是无法进一步细分的基本单元。 这些类型是不可变的,这意味着一旦分配它们就无法更改。 考虑更改整数的值没有多大意义。 如果要使用其他整数,只需分配其他整数即可。
By contrast, the string type is a composite type. Strings are reducible to smaller parts—the component characters. It might make sense to think of changing the characters in a string. But you can’t. In Python, strings are also immutable.
相反,字符串类型是复合类型。 字符串可简化为较小的部分-组成字符。 考虑更改字符串中的字符可能很有意义。 但是你不能。 在Python中,字符串也是不可变的。
The list is the first mutable data type you have encountered. Once a list has been created, elements can be added, deleted, shifted, and moved around at will. Python provides a wide range of ways to modify lists.
该列表是您遇到的第一个可变数据类型。 创建列表后,可以随意添加,删除,移动和移动元素。 Python提供了多种修改列表的方法。
修改单个列表值 (Modifying a Single List Value)
A single value in a list can be replaced by indexing and simple assignment:
列表中的单个值可以用索引和简单赋值代替:
You may recall from the tutorial Strings and Character Data in Python that you can’t do this with a string:
您可能会从Python的字符串和字符数据教程中回想起您无法使用字符串进行此操作:
>>> >>> s s = = 'foobarbaz'
'foobarbaz'
>>> >>> ss [[ 22 ] ] = = 'x'
'x'
Traceback (most recent call last):
File Traceback (most recent call last):
File "<stdin>", line "<stdin>" , line 1, in 1 , in <module>
<module>
TypeError: TypeError : 'str' object does not support item assignment
'str' object does not support item assignment
A list item can be deleted with the del
command:
可以使用del
命令删除列表项:
修改多个列表值 (Modifying Multiple List Values)
What if you want to change several contiguous elements in a list at one time? Python allows this with slice assignment, which has the following syntax:
如果要一次更改列表中的几个连续元素怎么办? Python允许通过切片分配来实现这一点,它具有以下语法:
aa [[ mm :: nn ] ] = = << iterableiterable >
>
Again, for the moment, think of an iterable as a list. This assignment replaces the specified slice of a
with <iterable>
:
再次,暂时将可迭代项视为列表。 这种分配替换的指定切片a
与<iterable>
:
The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed.
插入的元素数量不必等于替换的数量。 Python只是根据需要增加或缩小列表。
You can insert multiple elements in place of a single element—just use a slice that denotes only one element:
您可以插入多个元素来代替单个元素-只需使用仅表示一个元素的切片即可:
>>> >>> a a = = [[ 11 , , 22 , , 33 ]
]
>>> >>> aa [[ 11 :: 22 ] ] = = [[ 2.12.1 , , 2.22.2 , , 2.32.3 ]
]
>>> >>> a
a
[1, 2.1, 2.2, 2.3, 3]
[1, 2.1, 2.2, 2.3, 3]
Note that this is not the same as replacing the single element with a list:
请注意,这与用列表替换单个元素不同:
You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n]
(a zero-length slice) at the desired index:
您也可以在不删除任何内容的情况下将元素插入列表。 只需在所需的索引处指定[n:n]
形式的切片(零长度切片)即可:
>>> >>> a a = = [[ 11 , , 22 , , 77 , , 88 ]
]
>>> >>> aa [[ 22 :: 22 ] ] = = [[ 33 , , 44 , , 55 , , 66 ]
]
>>> >>> a
a
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the del
statement with the same slice:
您可以通过将适当的切片分配给空列表来删除列表中间的多个元素。 您还可以将del
语句用于同一切片:
在列表之前或之后添加项目 (Prepending or Appending Items to a List)
Additional items can be added to the start or end of a list using the +
concatenation operator or the +=
augmented assignment operator:
可以使用+
串联运算符或+=
扩充赋值运算符将其他项添加到列表的开头或结尾:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> a a += += [[ 'grault''grault' , , 'garply''garply' ]
]
>>> >>> a
a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> a a = = [[ 1010 , , 2020 ] ] + + a
a
>>> >>> a
a
[10, 20, 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
[10, 20, 'foo', 'bar', 'baz', 'qux', 'quux', 'corge']
Note that a list must be concatenated with another list, so if you want to add only one element, you need to specify it as a singleton list:
请注意,一个列表必须与另一个列表串联,因此,如果您只想添加一个元素,则需要将其指定为单例列表:
Note: Technically, it isn’t quite correct to say a list must be concatenated with another list. More precisely, a list must be concatenated with an object that is iterable. Of course, lists are iterable, so it works to concatenate a list with another list.
注意:从技术上讲,说一个列表必须与另一个列表串联是不太正确的。 更准确地说,列表必须与可迭代的对象连接在一起。 当然,列表是可迭代的,因此它可以将一个列表与另一个列表连接在一起。
Strings are iterable also. But watch what happens when you concatenate a string onto a list:
字符串也是可迭代的。 但是请注意将字符串连接到列表时会发生什么:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' ]
]
>>> >>> a a += += 'corge'
'corge'
>>> >>> a
a
['foo', 'bar', 'baz', 'qux', 'quux', 'c', 'o', 'r', 'g', 'e']
['foo', 'bar', 'baz', 'qux', 'quux', 'c', 'o', 'r', 'g', 'e']
This result is perhaps not quite what you expected. When a string is iterated through, the result is a list of its component characters. In the above example, what gets concatenated onto list a
is a list of the characters in the string 'corge'
.
此结果可能与您预期的不太一样。 遍历字符串时,结果是其组成字符的列表。 在上面的示例中,连接到列表a
是字符串'corge'
中的字符列表。
If you really want to add just the single string 'corge'
to the end of the list, you need to specify it as a singleton list:
如果您确实只想将单个字符串'corge'
到列表的末尾,则需要将其指定为单例列表:
If this seems mysterious, don’t fret too much. You’ll learn about the ins and outs of iterables in the tutorial on definite iteration.
如果这看起来很神秘,请不要担心太多。 您将在有关确定迭代的教程中了解可迭代的内容。
修改列表的方法 (Methods That Modify a List)
Finally, Python supplies several built-in methods that can be used to modify lists. Information on these methods is detailed below.
最后,Python提供了几种可用于修改列表的内置方法。 这些方法的详细信息如下。
Note: The string methods you saw in the previous tutorial did not modify the target string directly. That is because strings are immutable. Instead, string methods return a new string object that is modified as directed by the method. They leave the original target string unchanged:
注意:在上一教程中看到的字符串方法没有直接修改目标字符串。 那是因为字符串是不可变的。 而是,字符串方法返回一个新的字符串对象,该对象按照方法的指示进行了修改。 它们使原始目标字符串保持不变:
>>> >>> s s = = 'foobar'
'foobar'
>>> >>> t t = = ss .. upperupper ()
()
>>> >>> printprint (( ss , , tt )
)
foobar FOOBAR
foobar FOOBAR
List methods are different. Because lists are mutable, the list methods shown here modify the target list in place.
列表方法不同。 由于列表是可变的,因此此处显示的列表方法会修改目标列表。
a.append(<obj>)
a.append(<obj>)
Appends an object to a list.
将对象追加到列表。
a.append(<obj>)
appends object <obj>
to the end of list a
:
a.append(<obj>)
将对象<obj>
追加到列表a
的末尾:
Remember, list methods modify the target list in place. They do not return a new list:
请记住,列表方法会适当地修改目标列表。 他们不返回新列表:
>>> >>> a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>> x x = = aa .. appendappend (( 123123 )
)
>>> >>> printprint (( xx )
)
None
None
>>> >>> a
a
['a', 'b', 123]
['a', 'b', 123]
Remember that when the +
operator is used to concatenate to a list, if the target operand is an iterable, then its elements are broken out and appended to the list individually:
请记住,当使用+
运算符连接到列表时,如果目标操作数是可迭代的,则分解其元素并将其分别附加到列表中:
The .append()
method does not work that way! If an iterable is appended to a list with .append()
, it is added as a single object:
.append()
方法无法正常工作! 如果使用.append()
将iterable追加到列表中,则会将其作为单个对象添加:
>>> >>> a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>> aa .. appendappend ([([ 11 , , 22 , , 33 ])
])
>>> >>> a
a
['a', 'b', [1, 2, 3]]
['a', 'b', [1, 2, 3]]
Thus, with .append()
, you can append a string as a single entity:
因此,使用.append()
,您可以将字符串附加为单个实体:
a.extend(<iterable>)
a.extend(<iterable>)
Extends a list with the objects from an iterable.
用可迭代对象扩展列表。
Yes, this is probably what you think it is. .extend()
also adds to the end of a list, but the argument is expected to be an iterable. The items in <iterable>
are added individually:
是的,这可能就是您的想法。 .extend()
也会添加到列表的末尾,但是该参数应该是可迭代的。 <iterable>
中的项目是分别添加的:
>>> >>> a a = = [[ 'a''a' , , 'b''b' ]
]
>>> >>> aa .. extendextend ([([ 11 , , 22 , , 33 ])
])
>>> >>> a
a
['a', 'b', 1, 2, 3]
['a', 'b', 1, 2, 3]
In other words, .extend()
behaves like the +
operator. More precisely, since it modifies the list in place, it behaves like the +=
operator:
换句话说, .extend()
行为类似于+
运算符。 更准确地说,由于它修改了列表,因此其行为类似于+=
运算符:
a.insert(<index>, <obj>)
a.insert(<index>, <obj>)
Inserts an object into a list.
将对象插入列表。
a.insert(<index>, <obj>)
inserts object <obj>
into list a
at the specified <index>
. Following the method call, a[<index>]
is <obj>
, and the remaining list elements are pushed to the right:
a.insert(<index>, <obj>)
将对象<obj>
插入到指定<index>
处的列表a
中。 在方法调用之后, a[<index>]
是<obj>
,其余列表元素被推到右边:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> aa .. insertinsert (( 33 , , 3.141593.14159 )
)
>>> >>> aa [[ 33 ]
]
3.14159
3.14159
>>> >>> a
a
['foo', 'bar', 'baz', 3.14159, 'qux', 'quux', 'corge']
['foo', 'bar', 'baz', 3.14159, 'qux', 'quux', 'corge']
a.remove(<obj>)
a.remove(<obj>)
Removes an object from a list.
从列表中删除对象。
a.remove(<obj>)
removes object <obj>
from list a
. If <obj>
isn’t in a
, an exception is raised:
a.remove(<obj>)
从列表a
删除对象<obj>
。 如果<obj>
不在a
,将引发一个例外:
a.pop(index=-1)
a.pop(index=-1)
Removes an element from a list.
从列表中删除一个元素。
This method differs from .remove()
in two ways:
此方法与.remove()
有两点不同:
- You specify the index of the item to remove, rather than the object itself.
- The method returns a value: the item that was removed.
- 您指定要删除的项目的索引,而不是对象本身。
- 该方法返回一个值:被删除的项目。
a.pop()
simply removes the last item in the list:
a.pop()
只是删除列表中的最后一项:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> aa .. poppop ()
()
'corge'
'corge'
>>> >>> a
a
['foo', 'bar', 'baz', 'qux', 'quux']
['foo', 'bar', 'baz', 'qux', 'quux']
>>> >>> aa .. poppop ()
()
'quux'
'quux'
>>> >>> a
a
['foo', 'bar', 'baz', 'qux']
['foo', 'bar', 'baz', 'qux']
If the optional <index>
parameter is specified, the item at that index is removed and returned. <index>
may be negative, as with string and list indexing:
如果指定了可选的<index>
参数,那么将删除并返回该索引处的项目。 <index>
可能为负,如字符串和列表索引:
<index>
defaults to -1
, so a.pop(-1)
is equivalent to a.pop()
.
<index>
默认为-1
,因此a.pop(-1)
等同于a.pop()
。
列表是动态的 (Lists Are Dynamic)
This tutorial began with a list of six defining characteristics of Python lists. The last one is that lists are dynamic. You have seen many examples of this in the sections above. When items are added to a list, it grows as needed:
本教程首先列出了Python列表的六个定义特征。 最后一个是列表是动态的。 在上面的部分中,您已经看到了许多示例。 将项目添加到列表后,它会根据需要增长:
>>> >>> a a = = [[ 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' ]
]
>>> >>> aa [[ 22 :: 22 ] ] = = [[ 11 , , 22 , , 33 ]
]
>>> >>> a a += += [[ 3.141593.14159 ]
]
>>> >>> a
a
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
Similarly, a list shrinks to accommodate the removal of items:
同样,列表会缩小以容纳项目的删除:
Python元组 (Python Tuples)
Python provides another type that is an ordered collection of objects, called a tuple.
Python提供了另一种类型,即对象的有序集合,称为元组。
Pronunciation varies depending on whom you ask. Some pronounce it as though it were spelled “too-ple” (rhyming with “Mott the Hoople”), and others as though it were spelled “tup-ple” (rhyming with “supple”). My inclination is the latter, since it presumably derives from the same origin as “quintuple,” “sextuple,” “octuple,” and so on, and everyone I know pronounces these latter as though they rhymed with “supple.”
发音取决于您问的人。 有些人说它好像被拼写为“ to-ple”(用“ Mott the Hoople”押韵),而另一些人则说它被拼写为“ tup-ple”(押韵为“ supple”)。 我的倾向是后者,因为它大概来自与“五重奏”,“八重奏”,“八重奏”等相同的起源,而且我认识的每个人都将后者称为“柔顺”。
定义和使用元组 (Defining and Using Tuples)
Tuples are identical to lists in all respects, except for the following properties:
元组在所有方面均与列表相同,但以下属性除外:
- Tuples are defined by enclosing the elements in parentheses (
()
) instead of square brackets ([]
). - Tuples are immutable.
- 通过将元素括在圆括号(
()
)中而不是方括号([]
)中来定义元组。 - 元组是不可变的。
Here is a short example showing a tuple definition, indexing, and slicing:
这是一个简短的示例,显示元组定义,索引和切片:
>>> >>> t t = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' )
)
>>> >>> t
t
('foo', 'bar', 'baz', 'qux', 'quux', 'corge')
('foo', 'bar', 'baz', 'qux', 'quux', 'corge')
>>> >>> tt [[ 00 ]
]
'foo'
'foo'
>>> >>> tt [[ -- 11 ]
]
'corge'
'corge'
>>> >>> tt [[ 11 :::: 22 ]
]
('bar', 'qux', 'corge')
('bar', 'qux', 'corge')
Never fear! Our favorite string and list reversal mechanism works for tuples as well:
从不畏惧! 我们最喜欢的字符串和列表反转机制也适用于元组:
Note: Even though tuples are defined using parentheses, you still index and slice tuples using square brackets, just as for strings and lists.
注意:即使元组是使用括号定义的,您仍然可以使用方括号对元组进行索引和切片,就像字符串和列表一样。
Everything you’ve learned about lists—they are ordered, they can contain arbitrary objects, they can be indexed and sliced, they can be nested—is true of tuples as well. But they can’t be modified:
关于元组的所有知识(它们都是有序的,它们可以包含任意对象,可以对它们进行索引和切片,可以嵌套)也适用于元组。 但是它们不能被修改:
>>> >>> t t = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' , , 'quux''quux' , , 'corge''corge' )
)
>>> >>> tt [[ 22 ] ] = = 'Bark!'
'Bark!'
Traceback (most recent call last):
File Traceback (most recent call last):
File "<pyshell#65>", line "<pyshell#65>" , line 1, in 1 , in <module>
<module>
tt [[ 22 ] ] = = 'Bark!'
'Bark!'
TypeError: TypeError : 'tuple' object does not support item assignment
'tuple' object does not support item assignment
Why use a tuple instead of a list?
为什么使用元组而不是列表?
-
Program execution is faster when manipulating a tuple than it is for the equivalent list. (This is probably not going to be noticeable when the list or tuple is small.)
-
Sometimes you don’t want data to be modified. If the values in the collection are meant to remain constant for the life of the program, using a tuple instead of a list guards against accidental modification.
-
There is another Python data type that you will encounter shortly called a dictionary, which requires as one of its components a value that is of an immutable type. A tuple can be used for this purpose, whereas a list can’t be.
处理元组时,程序执行的速度比等效列表更快。 (当列表或元组较小时,这可能不会引起注意。)
有时您不希望修改数据。 如果集合中的值在程序生命期内保持恒定,则使用元组而不是列表可以防止意外修改。
您将很快遇到另一种Python数据类型,称为字典,它需要一个不可变类型的值作为其组件之一。 元组可以用于此目的,而列表则不能。
In a Python REPL session, you can display the values of several objects simultaneously by entering them directly at the >>>
prompt, separated by commas:
在Python REPL会话中,可以通过在>>>
提示符下直接输入多个对象的值(以逗号分隔)来同时显示多个对象的值:
Python displays the response in parentheses because it is implicitly interpreting the input as a tuple.
Python将响应显示在括号中,因为它会将输入隐式解释为元组。
There is one peculiarity regarding tuple definition that you should be aware of. There is no ambiguity when defining an empty tuple, nor one with two or more elements. Python knows you are defining a tuple:
关于元组定义,您应该注意一个特质。 定义一个空的元组时,没有歧义,也没有两个或多个元素。 Python知道您正在定义一个元组:
>>> >>> t t = = ()
()
>>> >>> typetype (( tt )
)
<class 'tuple'>
<class 'tuple'>
But what happens when you try to define a tuple with one item:
但是,当您尝试用一个项目定义一个元组时会发生什么:
>>> >>> t t = = (( 22 )
)
>>> >>> typetype (( tt )
)
<class 'int'>
<class 'int'>
Doh! Since parentheses are also used to define operator precedence in expressions, Python evaluates the expression (2)
as simply the integer 2
and creates an int
object. To tell Python that you really want to define a singleton tuple, include a trailing comma (,
) just before the closing parenthesis:
h! 由于括号也用于定义表达式中的运算符优先级,因此Python将表达式(2)
视为简单的整数2
并创建一个int
对象。 要告诉Python,您确实要定义一个单例元组,请在右括号前面加上一个逗号( ,
):
You probably won’t need to define a singleton tuple often, but there has to be a way.
您可能不需要经常定义单例元组,但是必须有一种方法。
When you display a singleton tuple, Python includes the comma, to remind you that it’s a tuple:
当显示单例元组时,Python会包含逗号,以提醒您这是一个元组:
>>> >>> printprint (( tt )
)
(2,)
(2,)
元组分配,打包和拆包 (Tuple Assignment, Packing, and Unpacking)
As you have already seen above, a literal tuple containing several items can be assigned to a single object:
如上所示,可以将包含多个项目的文字元组分配给单个对象:
When this occurs, it is as though the items in the tuple have been “packed” into the object:
发生这种情况时,就好像元组中的项目已“打包”到对象中:
![tuple packing](https://i-blog.csdnimg.cn/blog_migrate/5da1437adbaa55fa581f0e0e8644dd37.png)
>>> >>> t
t
('foo', 'bar', 'baz', 'qux')
('foo', 'bar', 'baz', 'qux')
>>> >>> tt [[ 00 ]
]
'foo'
'foo'
>>> >>> tt [[ -- 11 ]
]
'qux'
'qux'
If that “packed” object is subsequently assigned to a new tuple, the individual items are “unpacked” into the objects in the tuple:
如果随后将该“打包”对象分配给新的元组,则将各个项目“解包”到该元组中的对象中:
![元组拆包](https://i-blog.csdnimg.cn/blog_migrate/1d754c8d07e993d6f65d34a7b8396eb4.png)
When unpacking, the number of variables on the left must match the number of values in the tuple:
解压缩时,左侧的变量数必须与元组中的值数匹配:
>>> >>> (( s1s1 , , s2s2 , , s3s3 ) ) = = t
t
Traceback (most recent call last):
File Traceback (most recent call last):
File "<pyshell#16>", line "<pyshell#16>" , line 1, in 1 , in <module>
<module>
(( s1s1 , , s2s2 , , s3s3 ) ) = = t
t
ValueError: ValueError : too many values to unpack (expected 3)
too many values to unpack (expected 3)
>>> >>> (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = t
t
Traceback (most recent call last):
File Traceback (most recent call last):
File "<pyshell#17>", line "<pyshell#17>" , line 1, in 1 , in <module>
<module>
(( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = t
t
ValueError: ValueError : not enough values to unpack (expected 5, got 4)
not enough values to unpack (expected 5, got 4)
Packing and unpacking can be combined into one statement to make a compound assignment:
打包和拆包可以合并为一个语句以进行复合分配:
Again, the number of elements in the tuple on the left of the assignment must equal the number on the right:
同样,赋值左侧的元组中的元素数必须等于右侧的数:
>>> >>> (( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' )
)
Traceback (most recent call last):
File Traceback (most recent call last):
File "<pyshell#63>", line "<pyshell#63>" , line 1, in 1 , in <module>
<module>
(( s1s1 , , s2s2 , , s3s3 , , s4s4 , , s5s5 ) ) = = (( 'foo''foo' , , 'bar''bar' , , 'baz''baz' , , 'qux''qux' )
)
ValueError: ValueError : not enough values to unpack (expected 5, got 4)
not enough values to unpack (expected 5, got 4)
In assignments like this and a small handful of other situations, Python allows the parentheses that are usually used for denoting a tuple to be left out:
在这样的分配以及少数其他情况下,Python允许省略通常用于表示元组的括号:
It works the same whether the parentheses are included or not, so if you have any doubt as to whether they’re needed, go ahead and include them.
无论是否包含括号,其工作原理都是一样的,因此,如果您对是否需要括号存有疑问,请继续进行添加。
Tuple assignment allows for a curious bit of idiomatic Python. Frequently when programming, you have two variables whose values you need to swap. In most programming languages, it is necessary to store one of the values in a temporary variable while the swap occurs like this:
元组分配允许一些惯用的Python。 在编程时,经常有两个变量需要交换其值。 在大多数编程语言中,交换发生时,必须将值之一存储在临时变量中,如下所示:
>>> >>> a a = = 'foo'
'foo'
>>> >>> b b = = 'bar'
'bar'
>>> >>> aa , , b
b
('foo', 'bar')
('foo', 'bar')
>>># We need to define a temp variable to accomplish the swap.
>>># We need to define a temp variable to accomplish the swap.
>>> >>> temp temp = = a
a
>>> >>> a a = = b
b
>>> >>> b b = = temp
temp
>>> >>> aa , , b
b
('bar', 'foo')
('bar', 'foo')
In Python, the swap can be done with a single tuple assignment:
在Python中,可以通过一个元组分配完成交换:
As anyone who has ever had to swap values using a temporary variable knows, being able to do it this way in Python is the pinnacle of modern technological achievement. It will never get better than this.
正如任何曾经使用临时变量交换值的人都知道的那样,能够在Python中以这种方式进行操作是现代技术成就的巅峰之作。 它永远不会比这更好。
结论 (Conclusion)
This tutorial covered the basic properties of Python lists and tuples, and how to manipulate them. You will use these extensively in your Python programming.
本教程介绍了Python 列表和元组的基本属性,以及如何操作它们。 您将在Python编程中广泛使用它们。
One of the chief characteristics of a list is that it is ordered. The order of the elements in a list is an intrinsic property of that list and does not change, unless the list itself is modified. (The same is true of tuples, except of course they can’t be modified.)
列表的主要特征之一是它是有序的。 列表中元素的顺序是该列表的固有属性,并且除非更改列表本身,否则不会更改。 (对于元组,同样如此,但是当然不能对其进行修改。)
The next tutorial will introduce you to the Python dictionary: a composite data type that is unordered. Read on!
下一个教程将向您介绍Python 字典:一种无序的复合数据类型。 继续阅读!
翻译自: https://www.pybloggers.com/2018/07/lists-and-tuples-in-python/
python中字典列表元组