Python 列表操作指南

PythonBeginner
立即练习

介绍

在这个实验中,你将获得操作 Python 列表中(list)的实践经验。列表是存储有序项目集合的基本数据结构。你将学习如何创建、访问、添加、删除和修改列表元素。

此外,本实验将指导你完成更高级的操作,例如排序、查询和嵌套列表。完成本实验后,你将对如何有效地使用列表来管理和处理 Python 程序中的数据有一个扎实的理解。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 100%。获得了学习者 100% 的好评率。

创建和访问列表

在这一步,你将学习如何创建列表(list)以及访问它们的元素。列表是项目(item)的有序、可变集合(mutable collections),是 Python 最通用的数据类型之一。

列表使用方括号 [] 创建,元素之间用逗号分隔。让我们从创建几个列表开始。

在左侧的 WebIDE 文件浏览器中,找到并打开位于 ~/project 目录下的文件 list_creation.py。将以下代码添加到文件中:

## Create an empty list
empty_list = []
print("Empty list:", empty_list)
print("Type of empty_list:", type(empty_list))

## Create a list of numbers
numbers = [10, 20, 30, 40, 50]
print("Numbers list:", numbers)

## Lists can contain elements of different data types
mixed_list = [1, 'hello', 3.14, True]
print("Mixed data type list:", mixed_list)

## You can also create a list from another iterable, like a string
string_list = list("python")
print("List from a string:", string_list)

添加代码后,保存文件。要运行脚本,请在 WebIDE 中打开集成终端(integrated terminal)并执行以下命令:

python ~/project/list_creation.py

你应该会看到以下输出,它展示了创建列表的不同方法:

Empty list: []
Type of empty_list: <class 'list'>
Numbers list: [10, 20, 30, 40, 50]
Mixed data type list: [1, 'hello', 3.14, True]
List from a string: ['p', 'y', 't', 'h', 'o', 'n']

接下来,我们探索如何访问列表中的元素。你可以通过索引(位置)来访问元素。列表索引从 0 开始。你也可以使用负数索引,其中 -1 指向最后一个元素。

切片(Slicing)允许你访问一系列元素。语法是 list[start:stop:step]

将以下代码添加到 list_creation.py 文件的末尾:

## Accessing list elements
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
print("\n--- Accessing Elements ---")
print("Fruits list:", fruits)

## Access the first element (index 0)
print("First element:", fruits[0])

## Access the last element (index -1)
print("Last element:", fruits[-1])

## Slicing: get elements from index 1 up to (but not including) index 4
print("Slice [1:4]:", fruits[1:4])

## Slicing: get all elements from the beginning up to index 3
print("Slice [:3]:", fruits[:3])

## Slicing: get all elements from index 2 to the end
print("Slice [2:]:", fruits[2:])

## Slicing: get a copy of the entire list
print("Slice [:] (a copy):", fruits[:])

## Slicing with a step: get every second element
print("Slice [::2]:", fruits[::2])

## Slicing to reverse the list
print("Reversed list [::-1]:", fruits[::-1])

保存文件,并再次从终端运行脚本:

python ~/project/list_creation.py

观察新的输出,以了解索引和切片的工作原理:

Empty list: []
Type of empty_list: <class 'list'>
Numbers list: [10, 20, 30, 40, 50]
Mixed data type list: [1, 'hello', 3.14, True]
List from a string: ['p', 'y', 't', 'h', 'o', 'n']

--- Accessing Elements ---
Fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi']
First element: orange
Last element: kiwi
Slice [1:4]: ['apple', 'pear', 'banana']
Slice [:3]: ['orange', 'apple', 'pear']
Slice [2:]: ['pear', 'banana', 'kiwi']
Slice [:] (a copy): ['orange', 'apple', 'pear', 'banana', 'kiwi']
Slice [::2]: ['orange', 'pear', 'kiwi']
Reversed list [::-1]: ['kiwi', 'banana', 'pear', 'apple', 'orange']

你现在已经学会了如何创建列表及其内容。

修改列表:添加、删除和更改元素

在这一步,你将学习如何修改列表(list)。由于列表是可变的(mutable),你可以在创建它们之后添加、删除或更改它们的元素。

首先,我们关注添加元素。Python 提供了几种方法:

  • append(): 将单个元素添加到列表的末尾。
  • extend(): 将可迭代对象(如另一个列表)中的所有元素添加到末尾。
  • insert(): 在特定索引处插入一个元素。

在 WebIDE 文件浏览器中打开文件 list_modification.py。将以下代码添加到其中:

## --- Adding Elements ---
my_list = [1, 2, 3]
print("Original list:", my_list)

## Add an element using append()
my_list.append(4)
print("After append(4):", my_list)

## Add multiple elements using extend()
my_list.extend([5, 6])
print("After extend([5, 6]):", my_list)

## Insert an element at a specific position
my_list.insert(1, 1.5) ## Insert 1.5 at index 1
print("After insert(1, 1.5):", my_list)

保存文件,并从终端运行它:

python ~/project/list_modification.py

你的输出应该显示列表在每次操作后增长:

Original list: [1, 2, 3]
After append(4): [1, 2, 3, 4]
After extend([5, 6]): [1, 2, 3, 4, 5, 6]
After insert(1, 1.5): [1, 1.5, 2, 3, 4, 5, 6]

接下来,我们练习删除元素。关键方法包括:

  • remove(): 删除指定值第一次出现的位置的元素。
  • pop(): 删除并返回给定索引处的元素(如果未指定索引,则返回最后一个元素)。
  • del: 用于按索引删除项目或切片(slice)的语句。
  • clear(): 从列表中删除所有元素。

将以下代码添加到 list_modification.py 的末尾:

## --- Removing Elements ---
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']
print("\n--- Removing Elements ---")
print("Original fruits list:", fruits)

## Remove the last element using pop()
popped_item = fruits.pop()
print("After pop():", fruits)
print("Popped item:", popped_item)

## Remove an element by its value using remove()
fruits.remove('pear')
print("After remove('pear'):", fruits)

## Remove an element by its index using del
del fruits[1] ## Deletes 'apple' at index 1
print("After del fruits[1]:", fruits)

## Clear all elements from the list
fruits.clear()
print("After clear():", fruits)

最后,你可以通过为索引或切片(slice)分配一个新值来更改现有元素。将这最后一段代码添加到 list_modification.py 中:

## --- Changing Elements ---
letters = ['a', 'b', 'c', 'd', 'e']
print("\n--- Changing Elements ---")
print("Original letters list:", letters)

## Change a single element
letters[0] = 'A'
print("After changing index 0:", letters)

## Change a slice of elements
letters[1:3] = ['B', 'C']
print("After changing slice [1:3]:", letters)

保存文件,并再次运行脚本:

python ~/project/list_modification.py

完整的输出将展示你学到的所有修改技术:

Original list: [1, 2, 3]
After append(4): [1, 2, 3, 4]
After extend([5, 6]): [1, 2, 3, 4, 5, 6]
After insert(1, 1.5): [1, 1.5, 2, 3, 4, 5, 6]

--- Removing Elements ---
Original fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']
After pop(): ['orange', 'apple', 'pear', 'banana', 'kiwi']
Popped item: apple
After remove('pear'): ['orange', 'apple', 'banana', 'kiwi']
After del fruits[1]: ['orange', 'banana', 'kiwi']
After clear(): []

--- Changing Elements ---
Original letters list: ['a', 'b', 'c', 'd', 'e']
After changing index 0: ['A', 'b', 'c', 'd', 'e']
After changing slice [1:3]: ['A', 'B', 'C', 'd', 'e']

你现在已经熟练掌握了在 Python 列表中添加、删除和更改元素的方法。

高级列表操作:排序、查询和嵌套

在最后一步中,你将探索更高级的列表操作,包括排序(sorting)、查询信息(querying)以及处理嵌套列表(nested lists)。

我们从排序开始。sort() 方法会就地(in-place)修改列表。你可以按升序或降序排序。

在 WebIDE 中打开文件 list_operations.py。添加以下代码来演示排序:

## --- Sorting Lists ---
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print("--- Sorting Lists ---")
print("Original numbers list:", numbers)

## Sort the list in-place (ascending)
numbers.sort()
print("After sort():", numbers)

## Sort the list in descending order
numbers.sort(reverse=True)
print("After sort(reverse=True):", numbers)

## The reverse() method simply reverses the order, it does not sort
letters = ['a', 'b', 'c', 'd']
print("\nOriginal letters list:", letters)
letters.reverse()
print("After reverse():", letters)

保存文件,并从终端运行它:

python ~/project/list_operations.py

输出显示了排序和反转后的列表:

--- Sorting Lists ---
Original numbers list: [3, 1, 4, 1, 5, 9, 2, 6]
After sort(): [1, 1, 2, 3, 4, 5, 6, 9]
After sort(reverse=True): [9, 6, 5, 4, 3, 2, 1, 1]

Original letters list: ['a', 'b', 'c', 'd']
After reverse(): ['d', 'c', 'b', 'a']

接下来,我们查询列表以查找信息。

  • count(): 返回某个值出现的次数。
  • index(): 返回某个值第一次出现的索引。

将以下代码添加到 list_operations.py 中:

## --- Querying Lists ---
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print("\n--- Querying Lists ---")
print("Fruits list:", fruits)

## Count the occurrences of an element
apple_count = fruits.count('apple')
print("Count of 'apple':", apple_count)

## Find the index of the first occurrence of an element
banana_index = fruits.index('banana')
print("Index of first 'banana':", banana_index)

最后,我们来看一下嵌套列表(nested lists)。嵌套列表是指其元素包含其他列表的列表。这对于创建二维结构(如矩阵或网格)非常有用。

将最后这段代码添加到 list_operations.py 中:

## --- Nested Lists ---
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("\n--- Nested Lists ---")
print("Matrix:", matrix)

## Access an entire inner list (a row)
first_row = matrix[0]
print("First row:", first_row)

## Access a specific element in the nested list
## To get the element '6', we access row 1, then column 2
element = matrix[1][2]
print("Element at matrix[1][2]:", element)

保存文件,最后一次运行脚本:

python ~/project/list_operations.py

完整的输出将演示排序、查询和嵌套列表的访问:

--- Sorting Lists ---
Original numbers list: [3, 1, 4, 1, 5, 9, 2, 6]
After sort(): [1, 1, 2, 3, 4, 5, 6, 9]
After sort(reverse=True): [9, 6, 5, 4, 3, 2, 1, 1]

Original letters list: ['a', 'b', 'c', 'd']
After reverse(): ['d', 'c', 'b', 'a']

--- Querying Lists ---
Fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
Count of 'apple': 2
Index of first 'banana': 3

--- Nested Lists ---
Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
First row: [1, 2, 3]
Element at matrix[1][2]: 6

你现在已经掌握了处理 Python 列表的几种高级技术。

总结

在这个实验(Lab)中,你学习了操作 Python 列表的基础知识。你从使用方括号 []list() 构造函数创建列表开始。你练习了使用索引(indexing)和切片(slicing)来访问列表元素,这对于检索特定项目或列表的子集至关重要。

然后,你探索了如何通过 append()extend()insert() 添加元素,通过 remove()pop()del 删除元素,以及通过索引和切片赋值来更改元素来修改列表。最后,你学习了高级操作,包括使用 sort() 进行就地排序(in-place sorting)、使用 reverse() 反转、使用 count()index() 进行查询,以及使用嵌套列表(nested lists)构建数据结构。你现在已经具备了在 Python 项目中有效地使用列表的知识。