Flashield's Blog

Just For My Daily Diary

Flashield's Blog

Just For My Daily Diary

04.course-lists【列表】

Lists

Lists in Python represent ordered sequences of values. Here is an example of how to create them:

列表

Python 中的列表表示有序的值序列。 以下是如何创建它们的示例:

primes = [2, 3, 5, 7]

We can put other types of things in lists:

我们可以将其他类型的事物放入列表中:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

We can even make a list of lists:

我们甚至可以生成一个列表组成的列表:

hands = [
    ['J', 'Q', 'K'],
    ['2', '2', '2'],
    ['6', 'A', 'K'], # (Comma after the last element is optional)
]
# (I could also have written this on one line, but it can get hard to read)
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]

A list can contain a mix of different types of variables:

一个列表可以包含不同类型的变量:

my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)

Indexing

You can access individual list elements with square brackets.

Which planet is closest to the sun? Python uses zero-based indexing, so the first element has index 0.

索引

您可以使用方括号访问各个列表元素。

哪颗行星距离太阳最近? Python 使用从零开始的索引,因此第一个元素的索引为 0。

planets[0]
'Mercury'

What's the next closest planet?

下一个最近的行星是什么?

planets[1]
'Venus'

Which planet is furthest from the sun?

Elements at the end of the list can be accessed with negative numbers, starting from -1:

哪颗行星距离太阳最远

列表末尾的元素可以用负数访问,从-1开始:

planets[-1]
'Neptune'
planets[-2]
'Uranus'

Slicing

What are the first three planets? We can answer this question using slicing:

切片

前三颗行星是什么? 我们可以使用切片来回答这个问题:

planets[0:3]
['Mercury', 'Venus', 'Earth']

planets[0:3] is our way of asking for the elements of planets starting from index 0 and continuing up to but not including index 3.

The starting and ending indices are both optional. If I leave out the start index, it's assumed to be 0. So I could rewrite the expression above as:

planets[0:3] 是我们请求从索引 0 开始一直到但不包括索引 3 的 planets 元素的方法。

起始索引和结束索引都是可选的。 如果我省略起始索引,则假定它为 0。因此我可以将上面的表达式重写为:

planets[:3]
['Mercury', 'Venus', 'Earth']

If I leave out the end index, it's assumed to be the length of the list.

如果省略结束索引,则假定它是列表的长度。

planets[3:]
['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

i.e. the expression above means "give me all the planets from index 3 onward".

We can also use negative indices when slicing:

即上面的表达式的意思是“给我从索引 3 开始的所有行星”。

我们还可以在切片时使用负索引:

# All the planets except the first and last
planets[1:-1]
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']
# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']

Changing lists

Lists are "mutable", meaning they can be modified "in place".

One way to modify a list is to assign to an index or slice expression.

For example, let's say we want to rename Mars:

更改列表

列表是“可变的”,这意味着它们可以“就地”修改。

修改列表的一种方法是分配给索引或切片表达式。

例如,假设我们要重命名 Mars:

planets[3] = 'Malacandra'
planets
['Mercury',
 'Venus',
 'Earth',
 'Malacandra',
 'Jupiter',
 'Saturn',
 'Uranus',
 'Neptune']

Hm, that's quite a mouthful. Let's compensate by shortening the names of the first 3 planets.

嗯,真是够拗口的。 让我们通过缩短前 3 个行星的名称来进行补偿。

planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
# That was silly. Let's give them back their old names
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
['Mur', 'Vee', 'Ur', 'Malacandra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

List functions

Python has several useful functions for working with lists.

len gives the length of a list:

列表函数

Python 有几个有用的函数来处理列表。

len 给出列表的长度:

# How many planets are there?
len(planets)
8

sorted returns a sorted version of a list:

sorted 返回排序后的列表:

# The planets sorted in alphabetical order
sorted(planets)
['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']

sum does what you might expect:

sum 的作用符合您的预期:

primes = [2, 3, 5, 7]
sum(primes)
17

We've previously used the min and max to get the minimum or maximum of several arguments. But we can also pass in a single list argument.

我们之前使用过minmax来获取多个参数的最小值或最大值。 但我们也可以传入一个列表参数。

max(primes)
7

Interlude: objects

I've used the term 'object' a lot so far - you may have even read that everything in Python is an object. What does that mean?

In short, objects carry some things around with them. You access that stuff using Python's dot syntax.

For example, numbers in Python carry around an associated variable called imag representing their imaginary part. (You'll probably never need to use this unless you're doing some very weird math.)

插曲:对象

到目前为止,我已经多次使用过对象这个术语 - 您甚至可能读过Python 中的*一切*都是对象。 这意味着什么?

简而言之,物体随身携带着一些东西。 您可以使用 Python 的点语法来访问这些内容。

例如,Python 中的数字带有一个名为imag的关联变量,表示其虚部。 (除非你正在做一些非常奇怪的数学,否则你可能永远不需要使用它。)

x = 12
# x is a real number, so its imaginary part is 0.
print(x.imag)
# Here's how to make a complex number, in case you've ever been curious:
c = 12 + 3j
print(c.imag)
0
3.0

The things an object carries around can also include functions. A function attached to an object is called a method. (Non-function things attached to an object, such as imag, are called attributes).

For example, numbers have a method called bit_length. Again, we access it using dot syntax:

对象所携带的东西还可以包括功能。 附加到对象的函数称为方法。 (附加到对象的非功能事物,例如imag,称为属性)。

例如,数字有一个名为bit_length的方法。 再次,我们使用点语法访问它:

x.bit_length

To actually call it, we add parentheses:

为了实际调用它,我们添加括号:

x.bit_length()
4

Aside: You've actually been calling methods already if you've been doing the exercises. In the exercise notebooks q1, q2, q3, etc. are all objects which have methods called check, hint, and solution.

In the same way that we can pass functions to the help function (e.g. help(max)), we can also pass in methods:

旁白: 如果您一直在做练习,那么您实际上已经在调用方法了。 在练习笔记本中,q1q2q3等都是具有名为checkhintsolution的方法的对象。

就像我们可以将函数传递给 help 函数(例如 help(max))一样,我们也可以传入方法:

help(x.bit_length)
Help on built-in function bit_length:

bit_length() method of builtins.int instance
    Number of bits necessary to represent self in binary.

    >>> bin(37)
    '0b100101'
    >>> (37).bit_length()
    6

The examples above were utterly obscure. None of the types of objects we've looked at so far (numbers, functions, booleans) have attributes or methods you're likely ever to use.

But it turns out that lists have several methods which you'll use all the time.

上面的例子完全晦涩难懂。 到目前为止,我们所研究的对象类型(数字、函数、布尔值)都不具有您可能会使用的属性或方法。

但事实证明,列表有多种您将一直使用的方法。

List methods

列表的方法

list.append modifies a list by adding an item to the end:

list.append 通过在末尾添加一个项目来修改列表:

# Pluto is a planet darn it!
planets.append('Pluto')

Why does the cell above have no output? Let's check the documentation by calling help(planets.append).

Aside: append is a method carried around by all objects of type list, not just planets, so we also could have called help(list.append). However, if we try to call help(append), Python will complain that no variable exists called "append". The "append" name only exists within lists - it doesn't exist as a standalone name like builtin functions such as max or len.

为什么上面的单元格没有输出? 让我们通过调用help(planets.append)来检查文档。

旁白: append 是一个由列表类型的所有对象携带的方法,而不仅仅是 planets,所以我们也可以调用 help(list.append)。 然而,如果我们尝试调用 help(append),Python 会抱怨不存在名为append的变量。 append名称仅存在于列表中 - 它不像maxlen等内置函数那样作为独立名称存在。

help(planets.append)
Help on built-in function append:

append(object, /) method of builtins.list instance
    Append object to the end of the list.

The -> None part is telling us that list.append doesn't return anything. But if we check the value of planets, we can see that the method call modified the value of planets:

-> None 部分告诉我们 list.append 不返回任何内容。 但是如果我们检查planets的值,我们可以看到该方法的调用修改了planets的值:

planets
['Mercury',
 'Venus',
 'Earth',
 'Mars',
 'Jupiter',
 'Saturn',
 'Uranus',
 'Neptune',
 'Pluto']

list.pop removes and returns the last element of a list:

list.pop 删除并返回列表的最后一个元素:

planets.pop()
'Pluto'
planets
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Searching lists

Where does Earth fall in the order of planets? We can get its index using the list.index method.

搜索列表

地球在行星排列中排在什么位置? 我们可以使用list.index方法获取其索引。

planets.index('Earth')
2

It comes third (i.e. at index 2 - 0 indexing!).

At what index does Pluto occur?

它排在第三位(即索引 2 - 0 索引处!)。

冥王星出现在什么指数?

planets.index('Pluto')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In[30], line 1
----> 1 planets.index('Pluto')

ValueError: 'Pluto' is not in list

Oh, that's right...

To avoid unpleasant surprises like this, we can use the in operator to determine whether a list contains a particular value:

哦,原来如此……

为了避免这样令人不快的意外,我们可以使用in运算符来确定列表是否包含特定值:

# Is Earth a planet?
"Earth" in planets
True
# Is Calbefraques a planet?
"Calbefraques" in planets
False

There are a few more interesting list methods we haven't covered. If you want to learn about all the methods and attributes attached to a particular object, we can call help() on the object itself. For example, help(planets) will tell us about all the list methods:

还有一些我们没有介绍的更有趣的列表方法。 如果您想了解附加到特定对象的所有方法和属性,我们可以对该对象本身调用help()。 例如,help(planets)将告诉我们有关所有列表方法的信息:

help(planets)
Help on list object:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self

Click the "output" button to see the full help page. Lists have lots of methods with weird-looking names like __eq__ and __iadd__. Don't worry too much about these for now. (You'll probably never call such methods directly. But they get called behind the scenes when we use syntax like indexing or comparison operators.) The most interesting methods are toward the bottom of the list (append, clear, copy, etc.).

单击输出按钮查看完整的帮助页面。 列表有很多名称看起来很奇怪的方法,例如__eq____iadd__。 暂时不用太担心这些。 (您可能永远不会直接调用此类方法。但是当我们使用索引或比较运算符等语法时,它们会在幕后被调用。)最有趣的方法位于列表的底部(appendclear copy等)。

Tuples

Tuples are almost exactly the same as lists. They differ in just two ways.

1: The syntax for creating them uses parentheses instead of square brackets

元组

元组与列表几乎完全相同。 它们仅在两个方面有所不同。

1: 创建它们的语法使用括号而不是方括号

t = (1, 2, 3)
t = 1, 2, 3 # equivalent to above
t
(1, 2, 3)

2: They cannot be modified (they are immutable).

2: 它们不能被修改(它们是不可变的)。

t[0] = 100
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[36], line 1
----> 1 t[0] = 100

TypeError: 'tuple' object does not support item assignment

Tuples are often used for functions that have multiple return values.

For example, the as_integer_ratio() method of float objects returns a numerator and a denominator in the form of a tuple:

元组通常用于具有多个返回值的函数。

例如,float 对象的 as_integer_ratio() 方法以元组的形式返回分子和分母:

x = 0.125
x.as_integer_ratio()
(1, 8)

These multiple return values can be individually assigned as follows:

这多个返回值可以单独分配,如下所示:

numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
0.125

Finally we have some insight into the classic Stupid Python Trick™ for swapping two variables!

最后,我们对交换两个变量的经典 Stupid Python Trick™ 有了一些了解!

a = 1
b = 0
a, b = b, a
print(a, b)
0 1

Your Turn

You learn best by writing code, not just reading it. So try the coding challenge now.

到你了

最好的学习方式是编写代码,而不仅仅是阅读代码。 所以现在就尝试编码挑战

04.course-lists【列表】

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top