簡體   English   中英

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

[英]python generator for..in vs next()

我對python的生成器有點困惑,在它們上使用for循環與使用next()

我需要解析一個文本文件,該文件包含有關每行汽車的信息,每輛汽車的強制性行后有多個非強制性行,其型號名稱以a.開頭a. 所以我想以蟒蛇般的方式遍歷汽車。

我有以下代碼:

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相同的結果?

您每次都實例化生成器。 嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM