《Python数据分析技术栈》第02章 01 容器(Containers)

2024-01-19 08:52

本文主要是介绍《Python数据分析技术栈》第02章 01 容器(Containers),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

01 容器(Containers)

《Python数据分析技术栈》第02章 01 容器(Containers)

In the previous chapter, we saw that a variable could have a data type like int, float, str, and so on, but holds only a single value. Containers are objects that can contain multiple values. These values can have the same data type or different data types. The four built-in containers in Python are:
• Lists
• Tuples
• Dictionaries
• Sets

在上一章中,我们看到一个变量可以有 int、float、str 等数据类型,但只能保存一个值。容器是可以包含多个值的对象。这些值可以是相同的数据类型,也可以是不同的数据类型。Python 内置的四个容器是

  • 列表
  • 元组
  • 字典
  • 集合

Containers are also called iterables; that is, you can visit or traverse through each of the values in a given container object.

容器也被称为可迭代对象;也就是说,你可以访问或遍历给定容器对象中的每个值。

In the following sections, we discuss each container and its methods in more detail.

在下面的章节中,我们将更详细地讨论每个容器及其方法。

列表(Lists)

A list contains a set of values that are stored in sequential order. A list is mutable, that is, one can modify, add, or delete values in a list, making it a flexible container.

列表包含一组按顺序存储的值。列表是可变的,也就是说,人们可以修改、添加或删除列表中的值,使其成为一个灵活的容器。

An individual list item can be accessed using an index, which is an integer mentioned in square brackets, indicating the position of the item. The indexing for a list starts from 0.

可以使用索引访问单个列表项,索引是方括号中的整数,表示该列表项的位置。列表的索引从 0 开始。

Let us have a look at how to define and manipulate a list now.

现在让我们看看如何定义和操作列表。

定义列表(Defining a list)

A list can be defined by giving it a name and a set of values that are enclosed within square brackets.

给列表一个名称和一组值,并用方括号括起来,就可以定义列表。

colors=['violet','indigo','red','blue','green','yellow']

添加元素到列表(Adding items to a list)

Different methods can be used to add values to a list, explained in Table 2-1. The “colors” list created in the preceding code is used in the examples given in the below table.

可以使用不同的方法为列表添加值,详见表 2-1。下表中的示例使用了前面代码中创建的 "颜色 "列表。

Append: Adds one item at the end of a list. The method takes only a single value as an argument.

Append: 在列表末尾添加一个项目。该方法只接受一个值作为参数。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.append('white')
# the value 'white' is added after the last item in the 'colors' list

Insert: Adds one item at a given location or index. This method takes two arguments - the index and the value to be added.

Insert: 在给定位置或索引处添加一个项目。该方法需要两个参数–索引和要添加的值。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.insert(3, 'pink')
# the value 'pink' is added at the fourth position in the 'colors' list

Extend: Adds multiple elements (as a list) at the end of a given list. This method takes another list as an argument.

Extend: 在给定列表的末尾添加多个元素(作为一个列表)。此方法将另一个列表作为参数。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.extend(['purple', 'magenta'])
# values 'purple' and 'magenta' added at the end of the 'colors' list

从列表移除元素(Removing elements from a list)

Just as there are multiple ways of adding an item to a list, there is more than one way to remove values from a list, as explained in Table 2-2. Note that each of these methods can remove only a single item at a time.

正如向列表中添加项目有多种方法一样,从列表中移除值的方法也不止一种,详见表 2-2。请注意,每种方法一次只能删除一个项目。

The del keyword deletes an item at a given location.

del 关键字会删除指定位置上的项目。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
del colors[1]
# removes the second item of the 'colors' list

This method is used when the name of the item to be removed is known, but not its position.

该方法用于已知要删除的项目名称但不知道其位置的情况。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.remove('white')
# removes the item 'white' from the 'colors' list

This method removes and returns the last item in the list.

该方法删除并返回列表中的最后一个项目。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.pop()
# removes the last item and displays the item removed

从列表中查找元素(Finding the index (location) of an object in the list)

The index method is used to find out the location (or index) of a specific item or value in a list, as shown in the following statement.

索引方法用于查找特定项目或值在列表中的位置(或索引),如以下语句所示。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.index('violet')

计算列表的长度(Calculating the length of a list)

The len function returns the count of the number of items in a list, as shown in the following. The name of the list is passed as an argument to this function. Note that len is a function, not a method. A method can be used only with an object.

len 函数返回列表中条目个数的计数,如下所示。列表的名称作为参数传递给此函数。请注意,len 是一个函数,而不是一个方法。方法只能用于对象。

len(colors)

列表排序(Sorting a list)

The sort method sorts the values in the list, in ascending or descending order. By default, this method sorts the items in the ascending order. If the list contains strings, the sorting is done in alphabetical order (using the first letter of each string), as shown in the following.

排序方法按升序或降序对列表中的值进行排序。默认情况下,该方法按升序排序。如果列表中包含字符串,则按字母顺序排序(使用每个字符串的第一个字母),如下所示。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.sort()
print(colors)

Note that the list must be homogeneous (all values in the list should be of the same data type) for the sort method to work. If the list contains items of different data types, applying the sort method leads to an error.

请注意,列表必须是同质的(列表中的所有值应具有相同的数据类型),排序方法才会起作用。如果列表中包含不同数据类型的项目,应用排序方法时就会出错。

If you want to sort your elements in the reverse alphabetical order, you need to add the reverse parameter and set it to “True”, as shown in the following.

如果要按字母顺序反向排序元素,则需要添加反向参数并将其设置为 “True”,如下图所示。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors.sort(reverse=True)
print(colors)

Note that if you want to just reverse the order of the items in a list, without sorting the items, you can use the reverse method, as shown in the following.

请注意,如果只想颠倒列表中项目的顺序,而不想对项目进行排序,可以使用颠倒方法,如下图所示。

colors=['violet','indigo','red','blue','green','yellow']
colors.reverse()
print(colors)

列表切片(Slicing a list)

When we create a slice from a list, we create a subset of the original list by choosing specific values from the list, based on their position or by using a condition. Slicing of a list works similar to slicing a string, which we studied in the previous chapter.

当我们从列表中创建切片时,我们会根据列表中特定值的位置或使用条件从列表中选择特定值,从而创建原始列表的子集。列表切片的工作原理与我们在上一章学习的字符串切片类似。

To create a slice using an index, we use the colon operator (😃 and specify the start and stop values for the indexes that need to be selected.

要使用索引创建切片,我们需要使用冒号操作符(:),并为需要选择的索引指定起始值和停止值。

If we provide no start or stop value before and after the colon, it is assumed that the start value is the index of the first element (0), and the stop value is the index of the last element, as shown in the following statement.

如果我们在冒号前后没有提供起始值或终止值,则假定起始值为第一个元素的索引(0),终止值为最后一个元素的索引,如以下语句所示。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
print(colors[:])

We can also use the colon operator twice if we are using a step index. In the following statement, alternate elements of the list are extracted by specifying a step index of two.

如果使用步进索引,我们还可以使用两次冒号操作符。在下面的语句中,通过指定步进索引为 2 来提取列表中的备用元素。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
print(colors[::2])

Just like strings, lists follow both positive and negative indexing. Negative indexing (starts from –1, which is the index of the last element in the list) works from right to left, while positive indexing (starts from 0, which is the index of the first element in the list) works from left to right.

与字符串一样,列表也遵循正索引和负索引。负索引(从-1 开始,即列表中最后一个元素的索引)从右到左,而正索引(从 0 开始,即列表中第一个元素的索引)从左到右。

An example of slicing with negative indexing is shown in the following, where we extract alternate elements starting from the last value in the list.

下面是一个使用负索引进行切分的示例,我们从列表中的最后一个值开始提取交替元素。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
print(colors[-1:-8:-2])

从旧列表创建新列表(Creating new lists from existing lists)

列表生成式

There are three methods for creating a new list from an existing list – list comprehensions, the map function, and the filter function – which are explained in the following.

从现有列表创建新列表有三种方法–列表理解、map 函数和过滤器函数–下面将对这三种方法进行说明。

List comprehensions provide a shorthand and intuitive way of creating a new list from an existing list.

列表理解提供了一种从现有列表创建新列表的简便直观的方法。

Let us understand this with an example where we create a new list (‘colors1’) from the list (‘colors’) we created earlier. This list only contains only those items from the original list that contain the letter ‘e’.

让我们通过一个例子来理解这一点:我们从之前创建的列表(‘colors’)中创建一个新列表(‘colors1’)。该列表只包含原始列表中包含字母 "e "的项目。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']colors1 = [color for color in colors if 'e' in color]
print(colors1)

The structure of a list comprehension is explained in Figure 2-1. The output expression (‘color’) for items in the new list comes first. Next comes a for loop to iterate through the original list (note that other loops like the while loop are not used for iteration in a list comprehension). Finally, you can add an optional condition using the if/else construct.

图 2-1 解释了列表理解的结构。首先是新列表项的输出表达式(“颜色”)。接下来是一个 for 循环,对原始列表进行迭代(注意,列表理解中的迭代不使用其他循环,如 while 循环)。最后,可以使用 if/else 结构添加一个可选条件。

If we tried to create the same list without a list comprehension, using loops and conditions, the code would be more extended, as shown in the following.

如果我们不使用列表理解,而是使用循环和条件来创建相同的列表,代码将更加扩展,如下所示。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']# colors1 = [color for color in colors if 'e' in color]
colors1 = []
for color in colors:if 'e' in color:colors1.append(color)
print(colors1)

The critical point to keep in mind while using list comprehensions is that the readability of the code should not be compromised. If there are too many conditional expressions and loops involved in creating a new list, it is better to avoid list comprehensions.

在使用列表综合时,需要牢记的关键一点是不能影响代码的可读性。如果在创建新列表时涉及太多条件表达式和循环,最好避免使用列表综合。

Map函数(Map Function)

The map function is used to create a new list by applying a user-defined or inbuilt function on an existing list. The map function returns a map object, and we need to apply the list function to convert it to a list.

map 函数用于通过在现有列表上应用用户定义或内置函数来创建新列表。map 函数返回一个 map 对象,我们需要应用 list 函数将其转换为列表。

The map function accepts two arguments:
• The function to be applied
• The list on which the function is to be applied

map 函数接受两个参数:

  • 要应用的函数
  • 要应用该函数的列表

In the following example, we are creating a new list (‘colors1’) from the ‘colors’ list converting its elements to uppercase. An anonymous (lambda) function is used, which is followed by the name of the original list.

在下面的示例中,我们将从 "colors "列表创建一个新列表(“colors1”),并将其元素转换为大写字母。我们使用了一个匿名(lambda)函数,该函数后跟有原始列表的名称。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']
colors1 = map(lambda x: x.upper(), colors)
print(colors1)

The function returns a map object, and the list function needs to be used to convert it to a list.

该函数返回 map 对象,需要使用 list 函数将其转换为列表。

list(colors1)

Filter函数(Filter function)

The syntax of the filter function is similar to that of the map function. Whereas the map function returns all the objects in the original list after the function is applied, the filter function returns only those items that satisfy the condition specified when the filter function is called. Similar to the map function, we pass two arguments (a lambda function or a user-defined function, followed by the name of the list).

过滤器函数的语法与 map 函数类似。map 函数在应用函数后返回原始列表中的所有对象,而 filter 函数只返回满足调用 filter 函数时指定条件的项目。与 map 函数类似,我们传递两个参数(一个 lambda 函数或一个用户自定义函数,然后是列表的名称)。

In the following example, we are creating a list from the original list, keeping only those items that have less than five characters.

在下面的示例中,我们将从原始列表中创建一个列表,只保留少于 5 个字符的项目。

colors = ['violet', 'indigo', 'red', 'blue', 'green', 'yellow']colors2 = filter(lambda x: len(x) < 5, colors)
print(list(colors2))

Let us now discuss how we can iterate through two or more lists simultaneously.

现在让我们讨论一下如何同时遍历两个或多个列表。

使用zip遍历多个列表(Iterating through multiple lists using the zip function)

The zip function provides a way of combining lists and performing operations jointly on these lists, as shown in the following. The lists that need to be combined are passed as arguments to the list function.

zip 函数提供了一种组合列表并对这些列表联合执行操作的方法,如下所示。需要合并的列表作为参数传递给 list 函数。

# zip function and lists
colors = ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
color_ids = [1, 2, 3, 4, 5, 6, 7]
for i, j in zip(colors, color_ids):print(i, "has a serial number", j)

The zip function returns a list of tuples that are stored in an object of type “zip”. The type of this object needs to be changed to the list type to view the tuples.

zip 函数返回一个图元列表,这些图元存储在一个类型为 "zip "的对象中。要查看图元,需要将该对象的类型更改为列表类型。

# zip function and lists
colors = ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
color_ids = [1, 2, 3, 4, 5, 6, 7]
print(list(zip(colors, color_ids)))

The next function, enumerate, helps us access the indexes of the items in the list.

下一个函数 enumerate 可以帮助我们访问列表中项目的索引。

遍历列表索引(Accessing the index of items in a list)

The enumerate function is useful when you want to access the object as well as its index in a given list. This function returns a series of tuples, with each tuple containing the item and its index. An example of the usage of this function is shown in the following.

枚举函数在访问给定列表中的对象及其索引时非常有用。该函数返回一系列元组,每个元组包含项目及其索引。下面是一个使用该函数的示例。

# zip function and lists
colors = ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
for index, item in enumerate(colors):print(item, "occurs at index", index)

拼接列表(Concatenating of lists)

The concatenation of lists, where we combine two or more lists, can be done using the ‘+’ operator.

我们可以使用 "+"运算符对列表进行连接,将两个或更多列表组合在一起。

x = [1, 2, 3]
y = [3, 4, 5]
print(x + y)

We can concatenate any number of lists. Note that concatenation does not modify any of the lists being joined. The result of the concatenation operation is stored in a new object.

我们可以连接任意数量的列表。请注意,连接不会修改任何被连接的列表。连接操作的结果将存储在一个新对象中。

The extend method can also be used for the concatenation of lists. Unlike the ‘+’ operator, the extend method changes the original list.

extend 方法也可用于连接列表。与 "+"操作符不同,extend 方法会改变原始列表。

x = [1, 2, 3]
y = [3, 4, 5]
x.extend(y)
print(x)

Other arithmetic operators, like -, *, or /, cannot be used to combine lists.

其他算术运算符,如 -、* 或 /,不能用于组合列表。

To find the difference of elements in two lists containing numbers, we use list comprehension and the zip function, as shown in the following.

要找出两个包含数字的列表中元素的差值,我们可以使用列表理解和 zip 函数,如下所示。

x = [1, 2, 3]
y = [3, 4, 5]
d = [i - j for i, j in zip(x, y)]
print(d)

元组(Tuples)

A tuple is another container in Python, and like a list, it stores items sequentially. Like the items in a list, the values in a tuple can be accessed through their indexes. There are, however, some properties of tuples that differentiate it from lists, as explained in the following.

元组是 Python 中的另一种容器,和 list 一样,它按顺序存储项。与 list 中的项一样,元组中的值也可以通过索引来访问。但是,元组有一些不同于列表的属性,下面将对此进行解释。

Immutability: A tuple is immutable, which means that you cannot add, remove, or change the elements in a tuple. A list, on the other hand, permits all these operations.

不变性 元组是不可变的,这意味着你不能添加、删除或更改元组中的元素。而列表则允许所有这些操作。

Syntax: The syntax for defining a tuple uses round brackets (or parenthesis) to enclose the individual values (in comparison with the square brackets used for a list).

语法 定义元组的语法使用圆括号(或括号)括起各个值(与列表使用的方括号相比)。

Speed: In terms of speed of access and retrieval of individual elements, a tuple performs better than a list.

速度:就访问和检索单个元素的速度而言,元组的性能优于列表。

Let us now learn how to define a tuple and the various methods that can be used with a tuple.

现在让我们来学习如何定义元组以及元组的各种使用方法。

定义列表(Defining a tuple)

A tuple can be defined with or without the parenthesis, as shown in the following code.

元组的定义可以带括号,也可以不带括号,如下代码所示。

a = (1, 2, 3)
# can also be defined without parenthesis
b = 1, 2, 3
# A tuple can contain just a simple element
c = 1,
# Note that we need to add the comma even though there is no element following it because we are telling the interpreter that it is a tuple.

Just like a list, a tuple can contain objects of any built-in data type, like floats, strings, Boolean values, and so on.

与 list 一样,元组可以包含任何内置数据类型的对象,如浮点数、字符串、布尔值等。

元组的方法(Methods used with a tuple)

While tuples cannot be changed, there are a few operations that can be performed with tuples. These operations are explained in the following.

虽然无法更改元组,但可以对元组进行一些操作。下面将解释这些操作。

查询元素的个数(Frequency of objects in a tuple)

The count method is used to count the number of occurrences of a given value in a tuple:

计数方法用于计算给定值在元组中出现的次数:

x = (True, False, True, False, True)
print(x.count(True))

查询元素的索引(Location/Index of a tuple item)

The index method can be used to find the location of an item in a tuple. Using the tuple created in the previous statement, let us find the occurrence of the value, “False”.

索引方法可用于查找项目在元组中的位置。使用前面语句创建的元组,让我们查找值 "False "的出现位置。

x = (True, False, True, False, True)
print(x.index(False))

Only the location of the first occurrence of the item is returned by the index method.

索引方法只返回项目首次出现的位置。

元组解包(Tuple unpacking)

Tuple unpacking is the process of extracting the individual values in a tuple and storing each of these items in separate variables.

元组解包是提取元组中的各个值,并将每个项目存储到单独变量中的过程。

x = (True, False, True, False, True)
a, b, c, d, e = x
print(a, b, c, d, e)

If we do not know the number of items in a tuple, we can use the “*_” symbols to unpack the elements occurring after the first element into a list, as shown in the following.

如果我们不知道元组中的项数,我们可以使用 "*_"符号将第一个元素之后出现的元素解包为一个列表,如下图所示。

x = (True, False, True, False, True)
a, *_ = x
print(a, _)

元组的长度(Length of a tuple)

The length of a tuple can be calculated using the len function:

元组的长度可以使用 len 函数计算:

x = (True, False, True, False, True)
print(len(x))

元组的切片(Slicing of a tuple)

Slicing or creation of a smaller subset of values can be performed on tuples (similar to lists and strings in this respect).

可以对元组(在这方面类似于列表和字符串)进行分片或创建更小的值子集。

An example follows.

x[::-1]

元组的应用(Applications of tuples)

The following are some scenarios where tuples can be used.

下面是一些可以使用图元的情况。

创建包含元组的字典(Creating a dictionary with tuples)

A dictionary, which we discuss in detail in the next section, is a container containing a set of items (with a key mapping to a value). Tuples can be used for defining the items while creating a dictionary.

我们将在下一节详细讨论字典,它是一个容器,包含一组项(键映射到值)。在创建字典时,可以使用元组来定义项。

A dictionary item is a tuple, and a dictionary can be defined as a list of tuples using the dict method, as shown in the following.

字典项是一个元组,使用 dict 方法可以将字典定义为一个元组列表,如下所示。

x = dict([('color', 'pink'), ('flower', 'rose')])
print(x)

多项任务(Multiple assignments)

Tuple unpacking, as discussed earlier, is the process of separating a tuple into its components. This principle can be used for initializing multiple variables in one line, as shown in the following.

如前所述,元组拆包是将一个元组分离成其组成部分的过程。这一原理可用于在一行中初始化多个变量,如下所示。

# tuple unpacking
(a, b, c, d) = range(4)
print(a, b, c, d)

字典(Dictionaries)

A dictionary is a container that contains a set of items, with each item mapping a “key” to a “value”. Each individual item is also called a key/value pair. Some other points to note about a dictionary are:
• Unlike the values in lists and tuples, the items in a dictionary are not stored in sequential order.
• Dictionaries are mutable, like lists (i.e., one can make modifications to a dictionary object).
• Curly braces are used to enclose the items in a dictionary.

字典是包含一组项的容器,每个项映射一个 "键 "和一个 “值”。每个单独的项也称为键/值对。关于字典,还需注意以下几点

  • 与列表和元组中的值不同,字典中的项不是按顺序存储的。
  • 字典和列表一样是可变的(即可以修改字典对象)。
  • 大括号用于括起字典中的项目。

Let us understand how to define a dictionary and the different methods that can be used with a dictionary object.

让我们了解一下如何定义字典以及字典对象可以使用的不同方法。

定义字典(Defining a dictionary)

A dictionary is defined as a set of comma-separated key/value pairs enclosed within a pair of curly braces, as shown in the following code.

字典被定义为一组用逗号分隔的键/值对,括在一对大括号内,如下代码所示。

numbers = {'English': 'One', 'Spanish': 'Uno', 'German': 'Ein'}print(numbers)

“English”, “Spanish”, and “German” form the keys, while “One”, “Uno”, and “Ein” are the values in the dictionary.

“英语”、"西班牙语 "和 "德语 "构成键,而 “一”、"Uno "和 "Ein "则是字典中的值。

A dictionary can also be defined using the dict function, as explained earlier when we discussed tuples. The argument to this function is a list of tuples, with each tuple representing a key/value pair, as shown in the following.

字典也可以使用 dict 函数来定义,正如我们前面讨论元组时所解释的那样。该函数的参数是一个元组列表,每个元组代表一个键/值对,如下所示。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
print(numbers)

添加元素到字典(Adding an item (key/value pair) to a dictionary)

Using the key as an index, a new item can be added to a dictionary, as shown in the following.

使用键作为索引,可以向字典中添加新项目,如下所示。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
numbers['French'] = 'un'
print(numbers)
# A new key/value pair with the key as 'French' and value as 'un' has been added.

获取所有的值(Access the values in a dictionary)

The values method to access the values in a dictionary:

值方法来访问字典中的值:

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
numbers['French'] = 'un'
print(numbers.values())

获取所有的键值对(Access all the key/value pairs in a dictionary)

The items method is used to access the list of key/value pairs in a dictionary.

items 方法用于访问字典中的键/值对列表。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
numbers['French'] = 'un'
print(numbers.items())

获取特定的值(Accessing individual values)

The value corresponding to a given key can be retrieved using the key as an index, as shown in the following.

如下所示,可以使用键作为索引来检索给定键对应的值。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
print(numbers['German'])

The get method can also be used for retrieving values. The key is passed as an argument to this method, as shown in the following.

get 方法也可用于获取值。键作为参数传递给该方法,如下所示。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
print(numbers.get('German'))

The output is the same as that obtained in the previous statement.

输出结果与上一条语句相同。

设置默认值(Setting default values for keys)

The get method discussed in the preceding can also be used to add a key/value pair and set the default value for a key. If the key/value pair is already defined, the default value is ignored. There is another method, setdefault, which can also be used for this purpose.

前面讨论的 get 方法也可用于添加键/值对和设置键的默认值。如果键/值对已经定义,则默认值将被忽略。还有另一种方法 setdefault 也可用于此目的。

Note that the get method does not change the dictionary object, while the setdefault method ensures that the changes are reflected in the object.

请注意,get 方法不会更改字典对象,而 setdefault 方法可确保更改反映在对象中。

An example of the usage of the setdefault method is shown in the following.

下面举例说明 setdefault 方法的用法。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
numbers.setdefault('Mandarin', 'yi')
numbers.setdefault('Mandarin', 'yi222')
print(numbers)

As we can see, a new key/value pair is added.

正如我们所看到的,添加了一个新的键/值对。

An example of the get method is shown in the following.

获取方法的示例如下。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
print(numbers.get('Hindi', 'Ek'))

The value set by the get method is not added to the dictionary.

get 方法设置的值不会添加到字典中。

清空字典(Clearing a dictionary)

The clear method removes all the key/value pairs from a dictionary, in other words, it clears the contents of the dictionary without removing the variable from the memory.

clear 方法会删除字典中的所有键/值对,换句话说,它会清除字典中的内容,但不会从内存中删除变量。

numbers = dict([('English', 'One'), ('Spanish', 'Uno'), ('German', 'Ein')])
# removing all the key/value pairs
numbers.clear()
print(numbers)

集合(Sets)

A set is a container that contains elements that are not ordered or indexed. The primary characteristic of a set is that it is a collection of unique elements. Note that Python does not throw an error if we add duplicate elements while creating a set. However, while we perform operations on sets, all the duplicate elements are ignored, and only distinct elements are considered.

集合是一个容器,其中包含的元素没有排序或索引。集合的主要特征是它是唯一元素的集合。请注意,如果我们在创建集合时添加了重复元素,Python 不会抛出错误。然而,当我们对集合执行操作时,所有重复的元素都会被忽略,只有独特的元素才会被考虑。

定义集合(Set definition)

Just like a dictionary, a set is declared using curly braces and has unordered elements. However, while the values in a dictionary can be accessed using the keys as indexes, the values in a set cannot be accessed through indexes.

就像字典一样,集合也是使用大括号声明的,并且具有无序元素。不过,字典中的值可以使用键作为索引来访问,而集合中的值却不能通过索引来访问。

The following is an example of a set definition:

下面是一个集合定义示例:

a = {1, 1, 2}
print(a)

As we can see from the output, the duplicate value of 1 (which is present in the set definition) is ignored.

从输出结果可以看出,重复值 1(存在于集合定义中)被忽略。

集合操作(Set operations)

The methods and functions that can be used with sets are explained in Table 2-3.

表 2-3 介绍了可用于集合的方法和函数。

The len function counts the number of elements in a set, considering only the distinct values.

len 函数计算集合中元素的个数,只考虑不同的值。

len(a)

The for loop can iterate through a set and print its elements.

for 循环可以遍历一个集合并打印其元素。

for x in a:print(x)

A single item can be added to a set using the add method. For adding multiple values, the update method is used.

使用 add 方法可将单个项目添加到集合中。如果要添加多个值,则使用 update 方法。

a.add(3)
a.update([4,5])

Items can be removed using either the remove or the discard method.

可以使用移除或丢弃方法移除项目。

a = {1, 1, 2}
a.remove(1)
# Or
a.discard(2)
# Note: When we try to delete an element that is not in the set, the discard method does not give an error, whereas the remove method gives a KeyError.
print(a)

总结(Summary)

Now that we have covered all the essentials of the Python language - the concepts we learned in the previous chapter and what we understood in this chapter about the various containers and their methods, we need to decide which style or paradigm of programming to use. Among the various programming paradigms, which include procedural, functional, and object-oriented programming, we discuss object-oriented programming in the next section.

现在,我们已经掌握了 Python 语言的所有基本要素–上一章学到的概念和本章了解的各种容器及其方法,我们需要决定使用哪种编程风格或范式。在各种编程范式中,包括过程式编程、函数式编程和面向对象编程,我们将在下一节讨论面向对象编程。

这篇关于《Python数据分析技术栈》第02章 01 容器(Containers)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/621902

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【专题】2024飞行汽车技术全景报告合集PDF分享(附原数据表)

原文链接: https://tecdat.cn/?p=37628 6月16日,小鹏汇天旅航者X2在北京大兴国际机场临空经济区完成首飞,这也是小鹏汇天的产品在京津冀地区进行的首次飞行。小鹏汇天方面还表示,公司准备量产,并计划今年四季度开启预售小鹏汇天分体式飞行汽车,探索分体式飞行汽车城际通勤。阅读原文,获取专题报告合集全文,解锁文末271份飞行汽车相关行业研究报告。 据悉,业内人士对飞行汽车行业

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

hdu 2602 and poj 3624(01背包)

01背包的模板题。 hdu2602代码: #include<stdio.h>#include<string.h>const int MaxN = 1001;int max(int a, int b){return a > b ? a : b;}int w[MaxN];int v[MaxN];int dp[MaxN];int main(){int T;int N, V;s

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

金融业开源技术 术语

金融业开源技术  术语 1  范围 本文件界定了金融业开源技术的常用术语。 本文件适用于金融业中涉及开源技术的相关标准及规范性文件制定和信息沟通等活动。

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

K8S(Kubernetes)开源的容器编排平台安装步骤详解

K8S(Kubernetes)是一个开源的容器编排平台,用于自动化部署、扩展和管理容器化应用程序。以下是K8S容器编排平台的安装步骤、使用方式及特点的概述: 安装步骤: 安装Docker:K8S需要基于Docker来运行容器化应用程序。首先要在所有节点上安装Docker引擎。 安装Kubernetes Master:在集群中选择一台主机作为Master节点,安装K8S的控制平面组件,如AP

Spring框架5 - 容器的扩展功能 (ApplicationContext)

private static ApplicationContext applicationContext;static {applicationContext = new ClassPathXmlApplicationContext("bean.xml");} BeanFactory的功能扩展类ApplicationContext进行深度的分析。ApplicationConext与 BeanF