How to print the content of the generator?

2020-07-23 04:18发布

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

Results:

<generator object <genexpr> at 0x000000000108E780>

Why didn't it print?:

1
2
3

However the code:

sum(n for n in N) 

Will sum up all the number in N.

Could you please tell me why sum() worked but print() failed?

4条回答
兄弟一词,经得起流年.
2楼-- · 2020-07-23 04:55

Generator …

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)
查看更多
▲ chillily
3楼-- · 2020-07-23 04:56

It's because you passed a generator to a function and that's what __repr__ method of this generator returns. If you want to print what it would generate, you can use:

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

or

print(*(n for n in N), sep='\n') # Again, unpacks values

or

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

or if you like comprehensions:

[print(n) for n in N]

You have to be aware that the last method constructs a list filled with None.

查看更多
We Are One
4楼-- · 2020-07-23 04:58

If you don't want to cast it as a list, you can try:

print(*(n for n in N))

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

查看更多
劳资没心,怎么记你
5楼-- · 2020-07-23 05:04

You are literally printing a generator object representation

If you want on one line, try printing a list

print([n for n in N])

Which is just print(N)

If you want a line separated string, print that

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

Or write a regular loop and don't micro optimize the lines of code

查看更多
登录 后发表回答