我对python的生成器有点困惑,在它们上使用for
循环而不是使用next()
。在
我需要解析一个文本文件,其中包含关于每一行上的汽车的信息,每辆车在强制行后面有多个非强制行,其型号名称以a.
开头。所以我想用Python式的方式对汽车进行迭代。在
我有以下代码:
lines = """a. car1 model
b. car1 price
c. car1 details
a. car2 model
b. car2 price
a. car3 model
b. car3 price
c. car3 details
d. car3 comments
"""
def iter_cars(lineit):
res = []
for line in lineit:
if line.startswith('a') and res:
yield res
res = []
res.append(line)
yield res
# print the cars with next...,
lineit = iter(lines.split('\n'))
print(next(iter_cars(lineit)))
print(next(iter_cars(lineit)))
print(next(iter_cars(lineit)))
# reset the iterator and print the cars with for
lineit = iter(lines.split('\n'))
for car in iter_cars(lineit):
print(car)
输出是:
^{pr2}$为什么两种输出不同?为什么next()
在第一辆车之后跳过每辆车的a.
行?如何重写迭代器,使使用next()
产生与使用for..in
相同的结果?在
每次都要实例化生成器。试试这个
相关问题 更多 >
编程相关推荐