String join() method used with for loop

后端 未结 1 542
Happy的楠姐
Happy的楠姐 2021-01-22 06:24

I need your help, because I don\'t understand why is possible to use the join() method with a forloop as an argument.

Ex:

\" \"         


        
1条回答
  •  情话喂你
    2021-01-22 06:40

    The statement (str(x) for x in list) is called a generator expression:

    >>> (str(x) for x in [1,2,3])
     at 0x7fc916f01d20>
    

    What this does is create an object that can be iterated over exactly once, and yields elements that would be created one at a time. You can iterate over it as you would a list, like this:

    >>> gen = (str(x) for x in [1,2,3])
    >>> for s in gen:
    ...     print s
    ... 
    1
    2
    3
    

    A generator expression is iterable, so what the join function does is iterate over it and join its values.

    0 讨论(0)
提交回复
热议问题