matplotlib x,=... -这个结尾的逗号是逗号运算符吗?

nfzehxib  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(88)

我不明白变量lines后面的逗号是什么意思:http://matplotlib.org/examples/animation/simple_anim.html

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

字符串
如果我删除逗号,那么程序就被破坏了。完整的代码来自上面给出的URL:

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,变量后面的逗号似乎与只包含一个项的元组有关。

ltqd579y

ltqd579y1#

ax.plot()返回一个带有 one 元素的 tuple。通过在赋值目标列表中添加逗号,您可以要求Python将返回值解包并依次将其赋值给左侧命名的每个变量。
大多数情况下,你会看到这被应用于具有多个返回值的函数:

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

字符串
然而,左侧可以包含任意数量的元素,并且如果它是一个元组或变量列表,则将进行解包。
在Python中,逗号使某个东西成为元组:

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


括号在大多数地方都是可选的。你可以用 * 括号重写原始代码,而不改变其含义:

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


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

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


或者,你可以将它转换为不使用元组解包的行:

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


有关赋值如何在解包时工作的完整详细信息,请参阅赋值语句文档。

eit6fx6z

eit6fx6z2#

如果你有

x, = y

字符串
你解包一个长度为1的列表或元组。

x, = [1]


将导致x == 1,而

x = [1]


给出x == [1]

相关问题