概述
a = (x for x in range(10))
print(a)
print(type(a))
输出为:
<generator object <genexpr> at 0x000001BD5EDAD930>
<class 'generator'>
可见a是一个生成器
下面我们把它的元素输出:
1.
a = (x for x in range(10))
print(list(a))
输出为:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.
a = (x for x in range(10))
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
输出:
0
1
2
3
4
5
6
7
8
9
上面我们已经把a中的元素全部输出了,如果继续print的话就会出错
如下:
Traceback (most recent call last):
File "C:/Users/top/PycharmProjects/untitled4/venv/a_4.py", line 12, in <module>
print(next(a))
StopIteration
0
1
2
3
4
5
6
7
8
9
生成器,我们把它从头到尾遍历一遍,他就没了,如下:
a = (x for x in range(10))
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(type(a))
print('就算元素全没了,我还是generator!!!',list(a))
输出:
0
1
2
3
4
5
6
7
8
9
<class 'generator'>
就算元素全没了,我还是generator!!! []
或者:
a = (x for x in range(10))
print(list(a))#这个地方遍历了
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(type(a))
#print('就算元素全没了,我还是generator!!!',list(a))
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Traceback (most recent call last):
File "C:/Users/top/PycharmProjects/untitled4/venv/a_4.py", line 3, in <module>
print(a.__next__())
StopIteration
#这个
print(a)#不是遍历,提醒一下。
最后
以上就是贪玩鱼为你收集整理的python 遍历生成器元素的全部内容,希望文章能够帮你解决python 遍历生成器元素所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复