Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - What does the comma in this assignment statement do?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...