python3.X中, 初学迭代器iter()时遇到next()使用出现一直重复迭代第一个元素的情况怎样解决

其实很简单,虽然还暂时没明白原理,但是希望能帮助一些跟我一样的新手小白

在python3中,如果你这样编程:

l = 'assssss'
print(next(iter(l),'n'))
print(next(iter(l),'n'))

它的输出会是这样:

D:\PycharmProjects\one\venv\Scripts\python.exe ""
a
a

Process finished with exit code 0

或者这样编程:

l = 'assssss'
# print(next(iter(l),'n'))
# print(next(iter(l),'n'))

while True:
    try:
        x = iter(l).__next__()
        print(x)
    except StopIteration:
        break

它的输出会是

a
a
a
a
a
a
Process finished with exit code -1

但是你这样编程:

l = 'assssss'
# print(next(iter(l),'n'))
# print(next(iter(l),'n'))

# while True:
#     try:
#         x = iter(l).__next__()
#         print(x)
#     except StopIteration:
#         break
#
it = iter(l)
while True:
    try:
        x = it.__next__()
        print(x)
    except StopIteration:
        break

他就会正常输出:

a
s
s
s
s
s
s

Process finished with exit code 0

推理:规范编程从一点一滴开始!

你可能感兴趣的:(pygame)