gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:42 25 4
gpt4 key购买 nike

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

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

如果我删除逗号和变量“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()

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

最佳答案

ax.plot() 返回一个包含 一个 元素的元组。通过将逗号添加到赋值目标列表中,您可以要求 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

有关拆包方面作业如何工作的完整详细信息,请参阅 Assignment Statements文档。

关于python - x, = ... - 这个尾随逗号是逗号运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com