如何在 Python 中检查集合是否具有特定大小

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何在 Python 中检查一个集合是否具有特定的大小。本实验重点介绍如何使用 len() 函数来确定集合中元素的数量,这对于各种编程任务至关重要。

你将首先在 Python 脚本中创建一个包含数字和字符串的集合,然后使用 len() 函数来获取该集合的大小。最后,你将把集合的大小与期望的大小进行比较,以检查它们是否匹配。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/while_loops("While Loops") python/DataStructuresGroup -.-> python/sets("Sets") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} python/while_loops -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} python/sets -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} python/build_in_functions -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} python/using_packages -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} python/data_collections -.-> lab-559562{{"如何在 Python 中检查集合是否具有特定大小"}} end

理解集合大小

在这一步中,你将学习如何使用 len() 函数来确定集合中元素的数量。了解集合的大小对于各种编程任务至关重要,例如检查集合是否为空或比较不同集合的大小。

首先,让我们在 Python 脚本中创建一个简单的集合。在 LabEx 环境中打开你的 VS Code 编辑器,并在 ~/project 目录下创建一个名为 set_size.py 的新文件。

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

保存文件。现在,让我们运行这个脚本来查看输出。在 VS Code 中打开终端(你可以在底部面板找到它),并导航到 ~/project 目录(默认情况下你应该已经在该目录中)。使用以下命令执行脚本:

python set_size.py

你应该会看到以下输出:

{1, 2, 3, 4, 5}

现在我们有了一个集合,让我们来找出它包含多少个元素。在你的 set_size.py 脚本中添加以下代码行:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

保存更改并再次运行脚本:

python set_size.py

这次,你应该会看到以下输出:

{1, 2, 3, 4, 5}
The size of the set is: 5

len() 函数返回集合中元素的数量。在这种情况下,我们的集合 my_set 包含 5 个元素。

让我们尝试另一个包含字符串的集合的示例。将你的 set_size.py 脚本修改为以下内容:

## Create a set of strings
my_set = {"apple", "banana", "cherry"}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

保存文件并运行它:

python set_size.py

你应该会看到以下输出:

{'cherry', 'banana', 'apple'}
The size of the set is: 3

如你所见,len() 函数适用于包含不同类型数据的集合。

使用 len() 函数

在上一步中,你学习了如何使用 len() 函数来获取集合的大小。在这一步,我们将探索使用 len() 函数处理集合的更高级方法,包括在条件语句和循环中使用它。

让我们从修改 set_size.py 脚本开始,加入一个检查集合是否为空的条件语句。在 VS Code 编辑器中打开 set_size.py 文件,并按如下方式修改:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Check if the set is empty
if set_size == 0:
    print("The set is empty.")
else:
    print("The set is not empty.")

保存文件并运行:

python set_size.py

你应该会看到以下输出:

{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.

现在,让我们修改脚本以创建一个空集合并检查其大小。将 set_size.py 脚本的第一行修改为创建一个空集合:

## Create an empty set
my_set = set()

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Check if the set is empty
if set_size == 0:
    print("The set is empty.")
else:
    print("The set is not empty.")

保存文件并再次运行:

python set_size.py

这次,你应该会看到以下输出:

set()
The size of the set is: 0
The set is empty.

如你所见,对于空集合,len() 函数返回 0,并且我们的条件语句能正确识别该集合为空。

现在,让我们在循环中使用 len() 函数。假设我们要从集合中移除元素,直到集合为空。按如下方式修改 set_size.py 脚本:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Remove elements from the set until it is empty
while len(my_set) > 0:
    ## Remove an arbitrary element from the set
    element = my_set.pop()
    print("Removed element:", element)
    print("The set is now:", my_set)

print("The set is now empty.")

保存文件并运行:

python set_size.py

你应该会看到类似于以下的输出(移除元素的顺序可能会有所不同):

{1, 2, 3, 4, 5}
Removed element: 1
The set is now: {2, 3, 4, 5}
Removed element: 2
The set is now: {3, 4, 5}
Removed element: 3
The set is now: {4, 5}
Removed element: 4
The set is now: {5}
Removed element: 5
The set is now: set()
The set is now empty.

在这个示例中,我们在 while 循环的每次迭代中使用 len() 函数来检查集合是否为空。pop() 方法从集合中移除一个任意元素。循环会一直执行,直到集合为空。

与期望大小进行比较

在这一步中,你将学习如何使用条件语句将集合的大小与期望大小进行比较。当你需要在执行某些操作之前确保集合包含特定数量的元素时,这非常有用。

让我们修改 set_size.py 脚本,将集合的大小与期望大小进行比较。在 VS Code 编辑器中打开 set_size.py 文件,并按如下方式修改:

## Create a set of numbers
my_set = {1, 2, 3}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

保存文件并运行:

python set_size.py

你应该会看到以下输出:

{1, 2, 3}
The size of the set is: 3
The set is smaller than the desired size.

现在,让我们修改脚本以创建一个具有期望大小的集合。将 set_size.py 脚本的第一行修改为创建一个包含 5 个元素的集合:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

保存文件并再次运行:

python set_size.py

这次,你应该会看到以下输出:

{1, 2, 3, 4, 5}
The size of the set is: 5
The set has the desired size.

最后,让我们修改脚本以创建一个大于期望大小的集合。将 set_size.py 脚本的第一行修改为创建一个包含 7 个元素的集合:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5, 6, 7}

## Print the set
print(my_set)

## Get the size of the set using the len() function
set_size = len(my_set)

## Print the size of the set
print("The size of the set is:", set_size)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

保存文件并运行:

python set_size.py

你应该会看到以下输出:

{1, 2, 3, 4, 5, 6, 7}
The size of the set is: 7
The set is larger than the desired size.

这展示了如何使用 len() 函数将集合的大小与期望大小进行比较,并根据比较结果执行不同的操作。

总结

在本次实验中,你学习了如何使用 len() 函数来确定 Python 集合的大小。你创建了一个名为 set_size.py 的 Python 脚本,并在其中创建了包含数字和字符串的集合。然后使用 len() 函数来获取每个集合中的元素数量,展示了该函数在不同数据类型上的应用。

本次实验包括创建集合、打印其内容,然后使用 len() 函数获取并打印集合的大小。这个过程分别在整数集合和字符串集合上重复进行,加深了你对如何有效使用 len() 函数来确定集合中元素数量的理解。