# 创建列表迭代器
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
# 获取迭代器的下一个元素
print(next(my_iterator)) # 1
print(next(my_iterator)) # 2
print(next(my_iterator)) # 3
# 创建列表迭代器
my_list = [1, 2, 3]
my_iterator = iter(my_list)
# 获取迭代器的下一个元素,设置默认值为 None
print(next(my_iterator, None)) # 1
print(next(my_iterator, None)) # 2
print(next(my_iterator, None)) # 3
print(next(my_iterator, None)) # None
# 打开文件
lines = ['line 1\n', 'line 2\n', 'line 3\n']
with open('example.txt', 'w') as f:
f.writelines(lines)
file_path = "example.txt"
with open(file_path) as f:
# 创建文件迭代器
file_iterator = iter(f)
try:
while True:
# 逐行读取文件内容
line = next(file_iterator)
print(line, end="")
except StopIteration:
pass
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
# 使用自定义迭代器
my_iterator = MyIterator(1, 5)
print(next(my_iterator)) # 1
print(next(my_iterator)) # 2
print(next(my_iterator)) # 3
# 创建列表迭代器
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
# 跳过前两个元素
next(my_iterator)
next(my_iterator)
# 获取迭代器的下一个元素
print(next(my_iterator)) # 3
def infinite_sequence():
num = 0
while True:
yield num
num += 1
# 创建生成器
gen = infinite_sequence()
# 获取生成器的前几个元素
for _ in range(5):
print(next(gen))
# 创建嵌套列表
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 创建迭代器
iterator = iter(nested_list)
# 获取迭代器的下一个元素
print(next(iterator)) # [1, 2, 3]
print(next(iterator)) # [4, 5, 6]
print(next(iterator)) # [7, 8, 9]
0条评论