vs next()中..的python生成器

2024-09-30 04:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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相同的结果?在


Tags: theinformodellinerescarsprice

热门问题