How to print the content of the generator?

本小妞迷上赌 提交于 2019-12-21 23:13:59

问题


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

results:

<generator object <genexpr> at 0x000000000108E780>

why this code couldn't print:

1
2
3

However the code:

sum(n for n in N) 

could sum up all the number in N.

Could you please tell me why sum() could work but print() faild?


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/44616012/how-to-print-the-content-of-the-generator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!