[英]x, = ... - is this trailing comma the comma operator?
我不明白變量行后的逗號是什么意思: 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
有關賦值如何與解包相關的完整詳細信息,請參閱賦值語句文檔。
如果你有
x, = y
您解壓縮長度為 1 的列表或元組。 例如
x, = [1]
將導致x == 1
,而
x = [1]
給出x == [1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.