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

inz*_*zzz 35 python tuples matplotlib

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

line, = ax.plot(x, np.sin(x))
Run Code Online (Sandbox Code Playgroud)

如果我删除逗号和变量"line",变为变量"line",则程序被破坏.上面给出的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()
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 51

ax.plot()返回一个元组一个元件.通过将逗号添加到赋值目标列表,您可以要求Python解包返回值并将其分配给依次命名为左侧的每个变量.

大多数情况下,您会看到这适用于具有多个返回值的函数:

base, ext = os.path.splitext(filename)
Run Code Online (Sandbox Code Playgroud)

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

在Python中,它是使逗号成为元组的逗号:

>>> 1
1
>>> 1,
(1,)
Run Code Online (Sandbox Code Playgroud)

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

(line,) = ax.plot(x, np.sin(x))
Run Code Online (Sandbox Code Playgroud)

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

[line] = ax.plot(x, np.sin(x))
Run Code Online (Sandbox Code Playgroud)

或者,您可以将其重新编写为使用元组解包的行:

line = ax.plot(x, np.sin(x))[0]
Run Code Online (Sandbox Code Playgroud)

要么

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
Run Code Online (Sandbox Code Playgroud)

有关分配如何在解包方面工作的完整详细信息,请参阅分配语句文档.

  • 是的.如果它有帮助,你可以认为它相当于`line = ax.plot(x,np.sin(x))[0]` (4认同)
  • @Aya:除了`line, = ...` 语法会在右侧有0 个或超过1 个元素的iterable 中抛出异常,而使用索引只会在有0 个元素时抛出异常。 (2认同)

Elm*_*ise 20

如果你有

x, = y
Run Code Online (Sandbox Code Playgroud)

你解压缩长度为一的列表或元组.例如

x, = [1]
Run Code Online (Sandbox Code Playgroud)

会导致x == 1,而

x = [1]
Run Code Online (Sandbox Code Playgroud)

x == [1]