您的当前位置:首页正文

python如何遍历集合?

2024-07-17 来源:化拓教育网

python中遍历集合的方法:

1、使用for循环遍历

A = {'1','2','star'}
for item in A:
    print(item,end='')

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

2、使用while循环遍历

## 用while循环遍历
A = {'1','2','star'}
try:
    while True:
        print(A.pop(),end='')
except:
    pass

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。

更多Python知识请关注。