Files
Python_CookBook_repo/4.迭代器与生成器/1.手动访问迭代器中的元素.py
2025-09-10 16:12:45 +08:00

25 lines
712 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from scipy.stats import trim1
if __name__ == "__main__":
items = [1, 2, 3]
items = iter(items)
# 如果需要访问可迭代对象中的元素可以使用next函数
while True:
item = next(items, None)
if item is not None:
print(item)
else:
break
# next函数的第一个参数是一个可迭代对象第二个参数是None是没有元素的时候的返回值
# 如果不限制迭代器在没有元素后的返回值迭代器在迭代结束后会抛出一个StopIteration的错误
while True:
try:
item = next(items)
except StopIteration:
print("没东西了")
break