在Python中将str.join与生成器表达式一起使用 [英] Use str.join with generator expression in python
问题描述
当我阅读问题 Python string.join (列表)在对象数组而不是字符串数组上,我发现以下句子:
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)
我已经知道 (str(x)表示列表中的x)
是一个生成器表达式,我也知道生成器是可迭代的。以下代码验证了我的视图的正确性。
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
同时, str.join(iterable)
返回一个字符串,该字符串是iterable中字符串的串联。因此,下面的代码可以按我的意愿正常工作。
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])
毕竟,[1,2,3] 中x的 str(x)本身不是生成器。
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
推荐答案
这是在引入生成器表达式时指定的( PEP 289 ):
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]))
这篇关于在Python中将str.join与生成器表达式一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!