python生成器for..in vs next()

时间:2017-11-02 12:30:12

标签: python parsing for-loop iterator generator

我对python的生成器感到有点困惑,并使用for循环与使用next()

我需要解析一个文本文件,其中包含有关每条线路上的汽车的信息,每条汽车在强制线后面有多条非强制性线路,型号名称以a.开头。所以我想以pythonic的方式迭代汽车。

我有以下代码:

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)

,输出为:

# using next()
a. car1 model
b. car1 price
c. car1 details

b. car2 price

b. car3 price
c. car3 details
d. car3 comments


# using for..in
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

为什么两个输出不同?为什么next()在第一个之后跳过每辆车的a.行?如何重写迭代器,以便使用next()产生(轻笑)与使用for..in相同的结果?

1 个答案:

答案 0 :(得分:5)

每次都要实例化生成器。试试这个

gen = iter_cars(lineit)
print(next(gen))
print(next(gen))
print(next(gen))