ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-09-15 13:55:43  阅读:182  来源: 互联网

标签:python matplotlib tuples


我不明白变量行后的逗号是什么,意思是: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,matplotlib,tuples
来源: https://codeday.me/bug/20190915/1804989.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有