这个赋值语句中的逗号有什么作用? [英] What does the comma in this assignment statement do?

查看:28
本文介绍了这个赋值语句中的逗号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览我发现的一个有趣的示例脚本(在 this site,最后一个示例第 124 行),我正在努力理解 particles 后面的逗号在这一行中的作用:

particles, = ax.plot([], [], 'bo', ms=6)

如果省略逗号,脚本会出错,但语法(似乎类似于解包语句)对我来说没有多大意义,像

这样的语句

a, = [2,3]

失败,这似乎是反对拆包理论的论据.

任何见解将不胜感激.

解决方案

需要解包 1 元组(或任何其他长度为 1 的序列).示例:

<预><代码>>>>a,b = (1,2)>>>打印一个1>>>打印 b2>>>c, = (3,)>>>打印 c3>>>d = (4,)>>>打印(4,)

注意 c 和 d 之间的区别.

注意:

a, = (1,2)

失败,因为您需要左侧的项目数量与右侧的可迭代对象包含的项目数量相同.Python 3.x 稍微缓解了这一点:

Python 3.2.3(v3.2.3:3d0686d90f55,2012 年 4 月 10 日,11:09:56)[GCC 4.0.1 (Apple Inc. build 5493)] 在达尔文上输入帮助"、版权"、信用"或许可"以获取更多信息.>>>a,*rest = (1,2,3)>>>一种1>>>休息[2, 3]

I was looking through an interesting example script I found (at this site, last example line 124), and I'm struggling to understand what the comma after particles achieves in this line:

particles, = ax.plot([], [], 'bo', ms=6)

The script will hit an error if the comma is omitted, but the syntax (which seems to resemble an unpacking statement) does not make much sense to me, and a statement like

a, = [2,3]

fails, which seems like an argument against the unpacking theory.

Any insight would be greatly appreciated.

解决方案

It is needed to unpack the 1-tuple (or any other length-1 sequence). Example:

>>> a,b = (1,2)
>>> print a
1
>>> print b
2
>>> c, = (3,)
>>> print c
3
>>> d = (4,)
>>> print d
(4,)

Notice the difference between c and d.

Note that:

a, = (1,2)

fails because you need the same number of items on the left side as the iterable on the right contains. Python 3.x alleviates this somewhat:

Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:09:56) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a,*rest = (1,2,3)
>>> a
1
>>> rest
[2, 3]

这篇关于这个赋值语句中的逗号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆