如何遍历集合python
原创如何遍历集合Python
在Python中,遍历集合(set)的操作非常简单,集合是一种无序的、不重复的元素序列,因此遍历集合就是访问集合中的每一个元素。
使用for循环遍历集合
使用for循环可以遍历集合中的每一个元素,语法如下:
my_set = {1, 2, 3, 4, 5} for item in my_set: print(item)
输出结果为:
1 2 3 4 5
使用while循环遍历集合
除了使用for循环外,还可以使用while循环遍历集合中的元素,首先需要获取集合中的第一个元素,然后使用while循环不断访问集合中的下一个元素,直到访问完整个集合。
my_set = {1, 2, 3, 4, 5} i = iter(my_set) while True: try: item = next(i) print(item) except StopIteration: break
输出结果为:
1 2 3 4 5
使用列表生成式遍历集合
除了使用for循环和while循环外,还可以使用列表生成式遍历集合中的元素,列表生成式可以简洁地生成一个包含集合中所有元素的列表。
my_set = {1, 2, 3, 4, 5} my_list = [item for item in my_set] print(my_list)
输出结果为:
[1, 2, 3, 4, 5]
上一篇:python如何编写菜单 下一篇:python如何安装request