遍歷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]