【问题标题】:In Python, what is the purpose of a trailing comma in a return statement? [duplicate]在 Python 中,return 语句中尾随逗号的目的是什么? [复制]
【发布时间】:2017-12-26 23:24:21
【问题描述】:

animate_decay.py 的 matplotlib 示例中,return 语句使用尾随逗号,如:

return line,

并且该函数是普通函数,不是生成器函数。

所以,我编写了同一个函数的两个版本,一个带有尾随逗号,另一个没有:

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))

无论哪种情况,输出都是相同的:

尾随逗号 [1, 2, 3, 10]

没有尾随逗号 [1, 2, 3, 10]

语言规范 (Python 3.6) 没有特别提到 return 语句中的尾随逗号。我错过了什么吗?

【问题讨论】:

  • @user2357112 奇怪。您使用的是 Python 3.5,而我使用的是 3.6。我以我的输出发誓(你会的,以你的)。
  • , 在这种情况下是 tuple 文字,特别是具有单个值的元组(我正在运行 3.6 和类似 2.6、2.7、3.5 等。它导致 ([1, 2, 3, 10],) - 一个具有一个值的元组。
  • 在 3.6 上尝试仍然会产生一个带有逗号结尾的元组。

标签: python matplotlib return


【解决方案1】:

基本上在 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))

这段代码会产生:

The return type is <class 'list'>

The return type is <class 'tuple'>

您应该已经看到了打印输出的差异(即一个在元组中),但这可能是 3.6 的事情,我还不知道。

【讨论】:

  • 一个小问题,它不会将其转换为 tuple 它是 tuple 文字。就像您不会说 [1] 正在转换为 list 一样。尾随 , 只是一个值的 tuple 文字。
猜你喜欢
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2011-12-21
  • 1970-01-01
相关资源
最近更新 更多