簡體   English   中英

如何打印生成器的內容?

[英]How to print the content of the generator?

N = [1, 2, 3]
print(n for n in N)

結果:

<generator object <genexpr> at 0x000000000108E780>

為什么不打印?:

1
2
3

但是代碼:

sum(n for n in N) 

將 N 中的所有數字相加。

你能告訴我為什么 sum() 有效但 print() 失敗了嗎?

這是因為您將一個生成器傳遞給了一個函數,而這就是該生成器的__repr__方法返回的內容。 如果要打印它會生成的內容,可以使用:

print(*N, sep='\n') # * will unpack the generator

或者

print('\n'.join(map(str, N)))

請注意,一旦您檢索生成器的輸出以打印它,生成器就會耗盡- 嘗試再次對其進行迭代將不會產生任何項目。

您實際上是在打印生成器對象表示

如果您想在一行上,請嘗試打印列表

print([n for n in N])

這只是print(N)

如果你想要一個行分隔的字符串,打印

print("\n".join(map(str, N))) 

或者寫一個常規循環,不要微優化代碼行

如果您不想將其轉換為列表,可以嘗試:

print(*(n for n in N))

請參閱: https : //docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments

發電機 …

def  genfun():
    yield ‘A’
    yield ‘B’
    yield ‘C’
g=genfun()
print(next(g))= it will print 0th index .
print(next(g))= it will print 1st index.
print(next(g))= it will print 2nd index.
print(next(g))= it will print 3rd index But here in this case it will give Error as 3rd element is not there 
So , prevent from this error we will use for loop as below .
 for  i in g :
    print(i)

暫無
暫無

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

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