Use str.join with generator expression in python [duplicate]

故事扮演 提交于 2019-12-10 08:18:11

问题


When I read the question Python string.join(list) on object array rather than string array, I find the following sentence:

', '.join(str(x) for x in list)

I have already know about (str(x) for x in list) is a generator expression, I also know generator is an iterable. The following code verify the correctness of my view.

>>> gen = (x for x in [1,2,3])
<generator object <genexpr> at 0x104349b40>
>>> from collections import Iterable
>>> isinstance(gen, Iterable)
True

At the same time, str.join(iterable) return a string which is the concatenation of the strings in the iterable. So the following works fine as I wish.

>>> ",".join((str(x) for x in [1,2,3]))
'123'

Then here comes the question, why the code works fine too at bellow, why don't need a parentheses in the function call.

', '.join(str(x) for x in [1,2,3])

After all, str(x) for x in [1,2,3] itself is not a generator.

>>> tmp = str(x) for x in [1,2,3]
  File "<stdin>", line 1
    tmp = str(x) for x in [1,2,3]
                   ^
SyntaxError: invalid syntax

回答1:


This was specified when generator expressions were introduced (PEP 289):

if a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.

In your case it's a single positional argument, so both ways are possible:

', '.join(str(x) for x in [1,2,3])
', '.join((str(x) for x in [1,2,3]))



回答2:


After carefully reading the document word by word, I find it's mentioned Generator expressions:

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.




回答3:


It's a generator expression either way - but whether enclosing parentheses are required depends on the context within which the generator expression appears. Argument lists are a kind of special case: if the generator expression is the only argument, then enclosing parentheses aren't required (but can still be used, if you like). If a call has more than one argument, though, then enclosing parentheses are required. This is essentially point 2B in the PEP that introduced this feature.



来源:https://stackoverflow.com/questions/44014460/use-str-join-with-generator-expression-in-python

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