遍历set的方法有以下几种:
my_set = {1, 2, 3, 4, 5}
for element in my_set:
print(element)
set()
将set转换为列表,然后遍历列表:my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
for element in my_list:
print(element)
iter()
和next()
遍历set:my_set = {1, 2, 3, 4, 5}
my_iter = iter(my_set)
while True:
try:
element = next(my_iter)
print(element)
except StopIteration:
break
my_set = {1, 2, 3, 4, 5}
[element for element in my_set]