编写一个 Python 程序来遍历集合元素。for 循环是遍历集合元素最常用的方法。在此示例中,我们使用 for 循环遍历数字集合和字符串集合。
# Itearte Over Sets
set1 = {10, 20, 30, 40, 50, 60}
print("The Total Items in this Set = ")
for val in set1:
print(val, end = ' ')
set2 = set("Tutorial Gateway")
print("The Total Items in this Set = ")
for char in set2:
print(char, end = ' ')

Python 程序遍历集合元素
在这里,我们将集合转换为列表,并使用 for 循环范围根据索引迭代和打印集合元素。
# Itearte Over Sets
set1 = {11, 33, 55, 77, 99, 111}
list1 = list(set1)
print("The Total Items in this Set = ")
for i in range(len(list1)):
print(list1[i], end = ' ')
set2 = set("TutorialGateway")
list2 = list(set2)
print("\n\nThe Total Items in this Set = ")
for i in range(len(list2)):
print(list2[i], end = ' ')
使用 for 循环遍历集合元素的输出
The Total Items in this Set =
33 99 55 11 77 111
The Total Items in this Set =
l r G w u i y o t a e T
此程序使用 enumerate 遍历集合元素。通常,我们不需要 id。因此,您可以使用 for _, value in enumerate(setName)。
# Itearte Over Sets
set1 = {11, 33, 55, 77, 99, 111}
print("The Total Items in this Set = ")
for i, value in enumerate(set1):
print(i, value)
set2 = set("Python")
print("\nThe Total Items in this Set = ")
for i, value in enumerate(set2):
print(i, value)
print("\nThe Total Items in this Set = ")
for _, value in enumerate(set1):
print(value, end = ' ')
print("\nThe Total Items in this Set = ")
for _, value in enumerate(set2):
print(value, end = ' ')
使用 enumerate 遍历集合值的输出
The Total Items in this Set =
0 33
1 99
2 55
3 11
4 77
5 111
The Total Items in this Set =
0 y
1 o
2 n
3 t
4 P
5 h
The Total Items in this Set =
33 99 55 11 77 111
The Total Items in this Set =
y o n t P h
这是使用列表和列表推导式遍历集合的另一个示例。
# Itearte Over Sets
set1 = {5, 10, 20, 25, 30, 35, 40}
print("The Total Items in this Set = ")
x = [print(val, end = ' ') for val in set1]
set2 = set("Python")
print("The Total Items in this Set = ")
x = list(val for val in set2)
print(x)
print(*x)
使用列表推导式遍历集合元素的输出
The Total Items in this Set =
35 20 5 40 25 10 30 The Total Items in this Set =
['h', 'P', 'y', 'o', 't', 'n']
h P y o t n