Python 简明教程
Python - Loop Sets
Loop Through Set Items
在 Python 中循环遍历 set 项目是指迭代集合中的每个元素。我们稍后可以对每个项目执行所需的运算。这些运算包括列印列表元素、条件运算、过滤元素等。
Looping through set items in Python refers to iterating over each element in a set. We can later perform required operations on each item. These operation includes list printing elements, conditional operations, filtering elements etc.
与列表和元组不同,集合是无序集合,因此元素将按照任意顺序访问。你可以使用 for loop 迭代集合中的项目。
Unlike lists and tuples, sets are unordered collections, so the elements will be accessed in an arbitrary order. You can use a for loop to iterate through the items in a set.
Loop Through Set Items with For Loop
Python 中的 for 循环用于遍历序列(如列表、元组、字典、字符串或范围)或任何其他可迭代对象。它允许您为序列中的每个项目重复执行一个代码块。
A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.
在 for 循环中,你可以使用一个变量访问序列中的每个项目,这让你可以基于该项目的 value 执行运算或逻辑。我们可以使用 for 循环迭代集合项目,方法是迭代集合中的每个项目。
In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through set items using for loop by iterating over each item in the set.
Syntax
以下是使用 Python 中的 for 循环迭代集合中的项目的语法:
Following is the basic syntax to loop through items in a set using a for loop in Python −
for item in set:
# Code block to execute
Example
在以下示例中,我们正在使用 for 循环迭代集合“my_set”中的每个元素并检索每个元素:
In the following example, we are using a for loop to iterate through each element in the set "my_set" and retrieving each element −
# 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)
Output
以下是上面代码的输出: -
Following is the output of the above code −
Item: 100
Item: 25
Item: 10
Item: -21
Item: 12
Loop Through Set Items with While Loop
Python 中的 while 循环用于重复执行一段代码块,只要一个指定的条件计算为“True”。
A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to "True".
我们可以通过将集合转换为迭代器,然后迭代每个元素直至迭代器到达集合末尾,从而使用 while 循环迭代集合项目。
We can loop through set items using a while loop by converting the set to an iterator and then iterating over each element until the iterator reaches end of the set.
Example
在下面的示例中,我们正在使用迭代器和 while 循环迭代集合。 “try” 块检索并打印每个项目,而“except StopIteration” 块在没有更多项目可获取时中断循环:
In the below example, we are iterating through a set using an iterator and a while loop. The "try" block retrieves and prints each item, while the "except StopIteration" block breaks the loop when there are no more items to fetch −
# 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
Output
上述代码的输出如下:
Output of the above code is as follows −
Item: 1
Item: 2
Item: 3
Item: 4
Item: 5
Iterate using Set Comprehension
在 Python 中,集合推导式是通过迭代可迭代对象并选择性应用条件来创建集合的一种简洁方式。它用于生成集合,其语法类似于列表推导式,但结果是一个集合,确保所有元素都是唯一的和无序的。
A set comprehension in Python is a concise way to create sets by iterating over an iterable and optionally applying a condition. It is used to generate sets using a syntax similar to list comprehensions but results in a set, ensuring all elements are unique and unordered.
我们可以通过在花括号 {} 内定义集合推导式表达式并在表达式中指定迭代和条件逻辑来使用集合推导式进行迭代。以下为语法:
We can iterate using set comprehension by defining a set comprehension expression within curly braces {} and specifying the iteration and condition logic within the expression. Following is the syntax −
result_set = {expression for item in iterable if condition}
其中,
Where,
-
expression − It is an expression to evaluate for each item in the iterable.
-
item − It is a variable representing each element in the iterable.
-
iterable − It is a collection to iterate over (e.g., list, tuple, set).
-
condition − It is optional condition to filter elements included in the resulting set.
Example
在此示例中,我们正在使用集合推导式从原始列表“numbers”中生成一个包含偶数平方的集合:
In this example, we are using a set comprehension to generate a set containing squares of even numbers from the original list "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)
Output
我们得到了如下输出 −
We get the output as shown below −
{16, 4}
Iterate through a Set Using the enumerate() Function
Python中的enumerate()函数用于遍历可迭代对象,同时还提供每个元素的索引。
The enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element.
我们可以通过将集合转换为列表,然后再对 enumerate() 进行应用以遍历元素及其索引位置,从而使用 enumerate() 函数对集合进行迭代。以下是语法:
We can iterate through a set using the enumerate() function by converting the set into a list and then applying enumerate() to iterate over the elements along with their index positions. Following is the syntax −
for index, item in enumerate(list(my_set)):
# Your code here
Example
在以下示例中,我们首先将集合转换为列表。然后,我们使用带有 enumerate() 函数的 for 循环遍历该列表,获取每个项及其索引:
In the following example, we are first converting a set into a list. Then, we iterate through the list using a for loop with enumerate() function, retrieving each item along with its index −
# 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)
Output
下面显示了产生的输出:
The output produced is as shown below −
Index: 0 Item: 1
Index: 1 Item: 2
Index: 2 Item: 3
Index: 3 Item: 4
Index: 4 Item: 5
Loop Through Set Items with add() Method
Python 中的 add() 方法用于向集合中添加单个元素。如果集合中已经存在该元素,则集合保持不变。
The add() method in Python is used to add a single element to a set. If the element is already present in the set, the set remains unchanged.
要遍历集合项,我们使用 for 循环或集合推导等方法。
To loop through set items, we use methods like a for loop or set comprehension.
Example
在此示例中,我们遍历一个数字序列,并使用 add() 方法将每个数字添加到集合中。该循环迭代现有元素,而 add() 方法将新元素添加到集合中:
In this example, we loop through a sequence of numbers and add each number to the set using the add() method. The loop iterates over existing elements, while add() method adds new elements to the set −
# 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)
它将生成如下输出:
It will produce the following output −
{0, 1, 2, 3, 4}