python - Python 中的逗号是什么意思?

标签 python

我正在尝试在 pytorch 中学习反向传播,在那里我看到了这段代码:

def backward(ctx, grad_output):
        """
        In the backward pass we receive a Tensor containing the gradient of the loss
        with respect to the output, and we need to compute the gradient of the loss
        with respect to the input.
        """
        i, = ctx.saved_tensors
        grad_output = 2*i
        return grad_output

我不明白这里的i,是什么。

最佳答案

Python 可以解包值,例如,如果我们有一个元组

t = (2,3,'wat')

我们可以像这样将它的值赋给变量

coolnumber, othernumber, word = t

这将导致 word 被设置为 'wat'

如果我们的元组长度为1,我们需要区分将整个元组分配给一个变量

a = (1,)
# a is now (1,)

解压那个值

a, = (1,)
# a is now 1

关于python - Python 中的逗号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71851255/

相关文章:

python - 将 PyGame 黑白显示转换为 7x5 位矩阵

python - 混合 Tornado 和sqlalchemy

Python循环控制。避免悬挂环

python - 估计由一组点(Alpha 形状??)生成的图像区域

python - Django 模型 ON DELETE CASCADE 策略,改为模拟 ON DELETE RESTRICT,通用解决方案

python - 将字符串字段的 numpy 数组转换为数字格式

c# - 将 C# 中的值作为参数传递给 python,并从 Python 接收处理后的值并显示在 C# 表单上

python + argparse - 如何从命令行获取可选参数的顺序

python - Django 编辑子级中父级的字段

python - 用于 Python 的快速最大流最小切库