Ses*_*i R 0 python return matplotlib
在matplotlib 示例的animate_decay.py中,return语句与尾随逗号一起使用,如下所示:
return line,
Run Code Online (Sandbox Code Playgroud)
并且该函数是普通函数,而不是生成器函数。
所以,我编写了同一个函数的两个版本,一个带有尾随逗号,另一个没有:
def no_trailing_comma(x):
return x + [10]
def trailing_comma(x):
return x + [10],
data = [1, 2, 3]
print("With trailing comma", trailing_comma(data))
print("With no trailing comma", no_trailing_comma(data))
Run Code Online (Sandbox Code Playgroud)
无论哪种情况,输出都是相同的:
尾随逗号 [1, 2, 3, 10]
没有尾随逗号 [1, 2, 3, 10]
语言规范 (Python 3.6) 没有特别提及 return 语句中的尾随逗号。我错过了什么吗?
小智 9
基本上在 return 语句之后放置一个逗号将您返回的参数转换为包含该参数的元组。它根本不会影响参数的值,而是影响它的打包方式。使用您的示例函数
def no_trailing_comma(x):
return x + [10]
def trailing_comma(x):
return x + [10],
data = [1, 2, 3]
no_comma_value = no_trailing_comma(data)
comma_value = trailing_comma(data)
print("The return type is", type(no_comma_value))
print("The return type is", type(comma_value))
Run Code Online (Sandbox Code Playgroud)
此代码将产生:
The return type is <class 'list'>
The return type is <class 'tuple'>
Run Code Online (Sandbox Code Playgroud)
您应该已经看到打印输出的不同(即一个在元组中),但这可能是我还不知道的 3.6 的事情。
| 归档时间: |
|
| 查看次数: |
2567 次 |
| 最近记录: |