python 3 print generator

后端 未结 2 1189
独厮守ぢ
独厮守ぢ 2020-11-29 09:48

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:

>>&         


        
相关标签:
2条回答
  • 2020-11-29 10:21

    This behavior isn't too much different than on python2.x:

    Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
    [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> print (i*i for i in range(30))
    <generator object <genexpr> at 0x10c034a50>
    

    Generally speaking, if you want to actually know the items, a list might be easiest (it just requires the addition of a couple square brackets:

    print [i*i for i in range(30)]
    

    or on python3.x:

    print([i*i for i in range(30)])
    
    0 讨论(0)
  • 2020-11-29 10:22

    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 '\n' as an item separator:

    print(*generator_or_range_or_whatever, sep='\n')
    
    0 讨论(0)
提交回复
热议问题