x,= ...-此后缀逗号是逗号运算符吗? [英] x, = ... - is this trailing comma the comma operator?

查看:79
本文介绍了x,= ...-此后缀逗号是逗号运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白变量行后的逗号是什么,表示: http://matplotlib.org/examples/animation/simple_anim.html

line, = ax.plot(x, np.sin(x))

如果删除逗号和变量"line",则变为变量"line",则程序已损坏.上面给出的网址中的完整代码:

If I remove comma and variable "line," becomes variable "line" then program is broken. Full code from url given above:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 2*np.pi, 0.01)        # x-array
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
    interval=25, blit=True)
plt.show()

根据 http://docs.python.org/变量后的3/tutorial/datastructures.html#tuples-and-sequences 逗号似乎与仅包含一项的元组有关.

According to http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences comma after variable seems to be related to tuples containing only one item.

推荐答案

ax.plot()返回具有 one 元素的 tuple .通过在分配目标列表中添加逗号,您可以要求Python解开返回值并将其分配给依次命名为左侧的每个变量.

ax.plot() returns a tuple with one element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn.

通常,您会发现这适用于具有多个返回值的函数:

Most often, you see this being applied for functions with more than one return value:

base, ext = os.path.splitext(filename)

但是,左侧可以包含任意数量的元素,并且只要它是将进行解包的元组或变量列表即可.

The left-hand side can, however, contain any number of elements, and provided it is a tuple or list of variables the unpacking will take place.

在Python中,逗号使元组变成一个东西:

In Python, it's the comma that makes something a tuple:

>>> 1
1
>>> 1,
(1,)

在大多数位置,括号是可选的.您可以使用括号将原始代码重写为,而无需更改含义:

The parenthesis are optional in most locations. You could rewrite the original code with parenthesis without changing the meaning:

(line,) = ax.plot(x, np.sin(x))

或者您也可以使用列表语法:

Or you could use list syntax too:

[line] = ax.plot(x, np.sin(x))

或者,您可以将其重铸为不使用元组拆包的行:

Or, you could recast it to lines that do not use tuple unpacking:

line = ax.plot(x, np.sin(x))[0]

lines = ax.plot(x, np.sin(x))

def animate(i):
    lines[0].set_ydata(np.sin(x+i/10.0))  # update the data
    return lines

#Init only required for blitting to give a clean slate.
def init():
    lines[0].set_ydata(np.ma.array(x, mask=True))
    return lines

有关分配如何在拆包方面工作的完整详细信息,请参见转让声明文档.

For full details on how assignments work with respect to unpacking, see the Assignment Statements documentation.

这篇关于x,= ...-此后缀逗号是逗号运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆