What does the comma in this assignment statement do?

后端 未结 3 1114
梦如初夏
梦如初夏 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:37

    Have a look at what plot call returns. In your case it's a list with one element:

    >>> import matplotlib.pyplot as plt
    >>> ax = plt.gca()
    >>> ax.plot([], [], 'bo', ms=6)
    []
    

    Now it would more useful in this case to have a handle on the actual Line2D object, using unpacking with h, = ax.plot(...) rather than a spurious container around it as you would get with

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

    The latter would require you an extra step later on e.g.

    h[0].set_data(...)
    

    Return value of plot is always a list, because sometimes it needs to return more than one line object. It makes more sense to return even single lines inside a list, so that client code doesn't have to handle each case in a different way.


    The reason your unpacking a, = [2,3] fails is that there are 2 things to unpack on the right side, and only one variable. You would need to use a,b = [2,3] to unpack that.

提交回复
热议问题