What does the comma in this assignment statement do?

后端 未结 3 1116
梦如初夏
梦如初夏 2020-12-12 00:46

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

3条回答
  •  暖寄归人
    2020-12-12 01:18

    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]
    

提交回复
热议问题