介绍
在这个 Lab 中,你将全面了解 Python 中的元组(tuples)。你将学习如何创建元组、使用索引和切片访问它们的元素,并探索它们的不可变(immutable)特性。你还将练习使用元组运算符、解包(unpacking)以及常见的内置函数来高效地处理元组数据。
在这个 Lab 中,你将全面了解 Python 中的元组(tuples)。你将学习如何创建元组、使用索引和切片访问它们的元素,并探索它们的不可变(immutable)特性。你还将练习使用元组运算符、解包(unpacking)以及常见的内置函数来高效地处理元组数据。
在这个步骤中,你将学习如何创建元组以及访问它们的元素。元组是有序的、不可变的(immutable)项的集合,这意味着创建后其内容不能被更改。
首先,找到 WebIDE 左侧的文件浏览器(file explorer)。找到并打开名为 tuple_basics.py 的文件。我们将在该文件中编写代码。
让我们从创建几种不同类型的元组开始。将以下代码添加到 tuple_basics.py 中:
## Create an empty tuple
empty_tuple = ()
print("Empty tuple:", empty_tuple)
print("Type of empty_tuple:", type(empty_tuple))
## Create a tuple with a single element (note the trailing comma)
single_element_tuple = (50,)
print("\nSingle element tuple:", single_element_tuple)
print("Type of single_element_tuple:", type(single_element_tuple))
## Create a tuple with multiple elements
fruits = ("apple", "banana", "cherry")
print("\nFruits tuple:", fruits)
## Create a tuple from a list using the tuple() constructor
numbers_list = [1, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print("\nTuple from list:", numbers_tuple)
添加代码后,保存文件(你可以使用 Ctrl+S 快捷键)。然后,打开 WebIDE 底部的终端(terminal),并使用以下命令运行脚本:
python tuple_basics.py
你应该会看到以下输出,它确认了你的元组的创建和类型:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
现在,让我们学习如何访问元组内的元素。你可以使用索引(从 0 开始)来获取单个元素,使用切片(slicing)来获取元素的子序列。
将以下代码添加到 tuple_basics.py 文件的末尾:
## Define a sample tuple for accessing elements
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("\nOriginal tuple:", my_tuple)
## Access elements using indexing
print("First element (index 0):", my_tuple[0])
print("Last element (index -1):", my_tuple[-1])
## Access elements using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])
print("Elements from index 2 to the end:", my_tuple[2:])
print("Reverse the tuple:", my_tuple[::-1])
再次保存文件,并从终端运行脚本:
python tuple_basics.py
完整的输出现在将包含访问元组元素的结果:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
Original tuple: ('p', 'y', 't', 'h', 'o', 'n')
First element (index 0): p
Last element (index -1): n
Elements from index 1 to 3: ('y', 't', 'h')
Elements from index 2 to the end: ('t', 'h', 'o', 'n')
Reverse the tuple: ('n', 'o', 'h', 't', 'y', 'p')
你现在已经成功创建了元组并访问了它们的元素。
元组的一个关键特性是它们的不可变性(immutability)。这意味着一旦创建了元组,你就不能更改、添加或删除其元素。在这个步骤中,你将看到尝试修改元组时会发生什么,并学习通过创建新元组来实现“修改”的正确方法。
从文件浏览器中打开文件 tuple_modification.py。
首先,让我们尝试直接更改元组中的一个元素。将以下代码添加到 tuple_modification.py 中。尝试进行修改的那一行代码被注释掉了。
my_tuple = ('a', 'b', 'c', 'd', 'e')
print("Original tuple:", my_tuple)
## The following line will cause a TypeError because tuples are immutable.
## You can uncomment it to see the error for yourself.
## my_tuple[0] = 'f'
如果你取消注释倒数第二行代码并运行,Python 将会停止并显示一个 TypeError: 'tuple' object does not support item assignment 错误。
由于我们不能就地修改元组,解决方案是创建一个带有所需更改的新元组。我们可以使用切片(slicing)和拼接(concatenation,+ 运算符)来实现这一点。
将以下代码添加到 tuple_modification.py 的末尾,以查看如何“替换”一个元素:
## "Modify" a tuple by creating a new one
## Concatenate a new single-element tuple ('f',) with a slice of the original tuple
modified_tuple = ('f',) + my_tuple[1:]
print("New 'modified' tuple:", modified_tuple)
print("Original tuple is unchanged:", my_tuple)
类似地,你可以通过创建一个不包含该元素的新元组来“删除”一个元素。将此代码添加到你的文件中:
## "Delete" an element by creating a new tuple
## Concatenate the slice before the element with the slice after the element
tuple_after_deletion = my_tuple[:2] + my_tuple[3:] ## Excludes element at index 2 ('c')
print("\nNew tuple after 'deletion':", tuple_after_deletion)
保存文件,并从终端运行它:
python tuple_modification.py
输出将证明我们创建了新的元组,而原始元组保持不变:
Original tuple: ('a', 'b', 'c', 'd', 'e')
New 'modified' tuple: ('f', 'b', 'c', 'd', 'e')
Original tuple is unchanged: ('a', 'b', 'c', 'd', 'e')
New tuple after 'deletion': ('a', 'b', 'd', 'e')
这个步骤突出了元组的不可变特性,以及绕过此限制的标准做法。
Python 提供了几个有用的运算符来处理元组。你还将学习元组解包(tuple unpacking),这是一项强大的功能,允许你在单行代码中将元组的元素赋给变量。
从文件浏览器中打开文件 tuple_operators.py。
让我们探索拼接(concatenation,+)、重复(repetition,*)和成员资格(membership,in)运算符。将以下代码添加到 tuple_operators.py 中:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
## Concatenation (+)
concatenated_tuple = tuple1 + tuple2
print("Concatenated:", concatenated_tuple)
## Repetition (*)
repeated_tuple = tuple1 * 3
print("Repeated:", repeated_tuple)
## Membership (in)
is_present = 'b' in tuple2
print("\nIs 'b' in tuple2?", is_present)
is_absent = 5 in tuple1
print("Is 5 in tuple1?", is_absent)
保存文件并从终端运行它:
python tuple_operators.py
你将看到这些操作的结果:
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
接下来,让我们探索元组解包。这允许你在单行、易读的代码中将元组的元素分配给多个变量。变量的数量必须与元组中的元素数量相匹配。
将以下代码添加到 tuple_operators.py 的末尾:
## Tuple unpacking
person_info = ("Alice", 30, "Engineer")
name, age, profession = person_info
print("\nOriginal info tuple:", person_info)
print("Unpacked Name:", name)
print("Unpacked Age:", age)
print("Unpacked Profession:", profession)
再次保存文件并运行脚本:
python tuple_operators.py
输出现在将包括解包后的变量:
Concatenated: (1, 2, 3, 'a', 'b', 'c')
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 'b' in tuple2? True
Is 5 in tuple1? False
Original info tuple: ('Alice', 30, 'Engineer')
Unpacked Name: Alice
Unpacked Age: 30
Unpacked Profession: Engineer
元组解包在返回多个值的函数中特别有用,因为这些函数通常以元组的形式返回它们。
在这个最后一步中,你将学习使用常见的内置函数和方法来操作元组。元组主要有两个方法:count() 和 index(),并且可以与许多通用函数一起使用。
从文件浏览器中打开文件 tuple_functions.py。
让我们从元组方法开始。count() 返回一个元素出现的次数,而 index() 返回元素第一次出现的索引。
将以下代码添加到 tuple_functions.py 中:
my_tuple = (1, 5, 2, 8, 5, 3, 5, 9)
print("Tuple:", my_tuple)
## count() method
count_of_5 = my_tuple.count(5)
print("Count of 5:", count_of_5)
## index() method
index_of_8 = my_tuple.index(8)
print("Index of 8:", index_of_8)
现在,让我们使用一些对元组非常有用的内置函数,例如 len()、max()、min()、sum() 和 sorted()。
将以下代码添加到 tuple_functions.py 的末尾:
number_tuple = (10, 5, 20, 15, 30, 5)
print("\nNumber tuple:", number_tuple)
## len() function
print("Length:", len(number_tuple))
## max() and min() functions
print("Maximum value:", max(number_tuple))
print("Minimum value:", min(number_tuple))
## sum() function (for numeric tuples)
print("Sum of elements:", sum(number_tuple))
## sorted() function (returns a new sorted list)
sorted_list = sorted(number_tuple)
print("Sorted list from tuple:", sorted_list)
请注意,sorted() 函数返回一个新的列表(list),而不是元组。如果你需要一个排序后的元组,你可以使用 tuple(sorted_list) 将结果转换回来。
保存文件并从终端运行它:
python tuple_functions.py
你的输出应该如下所示:
Tuple: (1, 5, 2, 8, 5, 3, 5, 9)
Count of 5: 3
Index of 8: 3
Number tuple: (10, 5, 20, 15, 30, 5)
Length: 6
Maximum value: 30
Minimum value: 5
Sum of elements: 85
Sorted list from tuple: [5, 5, 10, 15, 20, 30]
你现在已经学会了使用重要的方法和函数来检查和分析元组。
在这个实验(Lab)中,你获得了使用 Python 元组(tuples)的坚实基础。你学习了如何以各种方式创建元组,以及如何使用索引(indexing)和切片(slicing)来访问它们的元素。你探索了元组不可变性(immutability)的核心概念,并练习了创建新元组来执行“修改”。你还熟悉了常见的元组运算符,如 + 和 *,元组解包的便利性,以及内置方法(count()、index())和函数(len()、max()、sorted())在处理元组数据时的实用性。