Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python 3 print generator

There is a problem when i deal with print() function(Python 3).

When I'm looking for sum of a series I may use the following code pattern:

>>> sum(i for i in range(101))

But when I tend to check the series that I had made: (I choose print() and assume it will print out line by line)

>>> print(i for i in range(101))

It turns out become a generator object without value return. So I have to used list() for series checking. Is that a flaw in print function?

PS: The above written is an example to form a generator, not the simplest form for natural series but the bone structure for complex series. In order for convenience in series values checking, I am looking for a way to print out each value line by line.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sum takes an iterable of things to add up, while print takes separate arguments to print. If you want to feed all the generator's items to print separately, use * notation:

print(*(i for i in range(1, 101)))

You don't actually need the generator in either case, though:

sum(range(1, 101))
print(*range(1, 101))

If you want them on separate lines, you're expecting the behavior of multiple individual calls to print, which means you're expecting the behavior of a regular loop:

for item in generator_or_range_or_whatever:
    print(item)

though you also have the option of specifying ' ' as an item separator:

print(*generator_or_range_or_whatever, sep='
')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...