循环遍历 Set Items
在 Python 中遍历 set 项是指遍历 set 中的每个元素。我们稍后可以对每个项目执行所需的操作。这些操作包括列表打印元素、条件操作、过滤元素等。
与列表和 Tuples 不同,集合是无序的集合,因此将按任意顺序访问元素。您可以使用 for 循环遍历 Set 中的项。
使用 For 循环遍历 Set Items
Python 中的 for 循环用于迭代序列(如列表、元组、字典、字符串或范围)或任何其他可迭代对象。它允许您为序列中的每个项目重复执行一个代码块。
在 for 循环中,您可以使用变量访问序列中的每个项目,从而允许您根据该项目的值执行操作或逻辑。我们可以通过迭代集合中的每个项目来使用 for 循环遍历集合项。
语法
以下是在 Python 中使用 for 循环遍历集合中项目的基本语法 -
for item in set:
# Code block to execute
例
在下面的示例中,我们使用 for 循环遍历集合 “my_set” 中的每个元素并检索每个元素 -
# Defining a set with multiple elements
my_set = {25, 12, 10, -21, 10, 100}
# Loop through each item in the set
for item in my_set:
# Performing operations on each element
print("Item:", item)
输出
以下是上述代码的输出 -
Item: 25
Item: 10
Item: -21
Item: 12
使用 While 循环遍历设置项
Python 中的 while 循环用于重复执行代码块,只要指定的条件计算结果为 “True”。
我们可以使用 while 循环遍历集合项,方法是将集合转换为迭代器,然后迭代每个元素,直到迭代器到达集合的末尾。
例
在下面的示例中,我们使用迭代器和 while 循环遍历集合。“try” 块检索并打印每个项目,而 “except StopIteration” 块在没有更多项目要获取时中断循环 -
# Defining a set with multiple elements
my_set = {1, 2, 3, 4, 5}
# Converting the set to an iterator
set_iterator = iter(my_set)
# Looping through each item in the set using a while loop
while True:
try:
# Getting the next item from the iterator
item = next(set_iterator)
# Performing operations on each element
print("Item:", item)
except StopIteration:
# If StopIteration is raised, break from the loop
break
输出
上述代码的输出如下 -
Item: 2
Item: 3
Item: 4
Item: 5
使用 Set Comprehension 进行迭代
Python 中的集合推导式是一种通过迭代可迭代对象并选择性地应用条件来创建集合的简洁方法。它用于使用类似于列表推导式的语法生成集合,但会生成一个集合,确保所有元素都是唯一且无序的。
我们可以通过在大括号 {} 中定义集合推导表达式并在表达式中指定迭代和条件逻辑来使用集合推导进行迭代。以下是语法 -
result_set = {expression for item in iterable if condition}
哪里
- 表达式 − 它是一个表达式,用于对可迭代对象中的每个项目进行求值。
- 项 − 它是一个变量,表示可迭代对象中的每个元素。
- 可迭代 - 它是一个要迭代的集合(例如,list、tuple、set)。
- 条件 - 筛选结果集中包含的元素是可选条件。
在这个例子中,我们使用集合推导式来生成一个包含原始列表 “numbers” 中偶数平方的集合 -
# Original list
numbers = [1, 2, 3, 4, 5]
# Set comprehension to create a set of squares of even numbers
squares_of_evens = {x**2 for x in numbers if x % 2 == 0}
# Print the resulting set
print(squares_of_evens)
输出
我们得到的输出如下所示 -
使用 enumerate() 函数遍历 Set
Python 中的 enumerate() 函数用于迭代可迭代对象,同时还提供每个元素的索引。
我们可以使用 enumerate() 函数遍历集合,方法是将集合转换为列表,然后应用 enumerate() 遍历元素及其索引位置。以下是语法 -
for index, item in enumerate(list(my_set)):
# Your code here
例
在以下示例中,我们首先将 set 转换为 list。然后,我们使用带有 enumerate() 函数的 for 循环遍历列表,检索每个项目及其索引 -
# Converting the set into a list
my_set = {1, 2, 3, 4, 5}
set_list = list(my_set)
# Iterating through the list
for index, item in enumerate(set_list):
print("Index:", index, "Item:", item)
输出
生成的输出如下所示 -
Index: 1 Item: 2
Index: 2 Item: 3
Index: 3 Item: 4
Index: 4 Item: 5
使用 add() 方法遍历 Set Items
Python 中的 add() 方法用于将单个元素添加到集合中。如果该元素已存在于 set 中,则 set 将保持不变。
为了遍历 set items,我们使用 for 循环或 set comprehension 等方法。
例在这个例子中,我们遍历一个数字序列,并使用 add() 方法将每个数字添加到集合中。循环迭代现有元素,而 add() 方法将新元素添加到集合中 -
# Creating an empty set
my_set = set()
# Looping through a sequence and adding elements to the set
for i in range(5):
my_set.add(i)
print(my_set)
它将产生以下输出 -