unpack the first two elements in list/tuple

后端 未结 5 1397
小蘑菇
小蘑菇 2020-12-29 01:30

Is there a way in python to do like this:

a, b, = 1, 3, 4, 5

And then:

>>> a
1
>>> b
3

相关标签:
5条回答
  • 2020-12-29 01:52

    On Python 3 you can do the following:

    >>> a, b, *_ = 1, 3, 4, 5
    >>> a
    1
    >>> b
    3
    

    _ is just a place holder for values you don't need

    0 讨论(0)
  • 2020-12-29 01:56

    There is no way to do it with the literals that you've shown. But you can slice to get the effect you want:

    a, b = [1, 3, 4, 5, 6][:2]
    

    To get the first two values of a list:

    a, b = my_list[:2]
    
    0 讨论(0)
  • 2020-12-29 01:59

    Just to add to Nolen's answer, in Python 3, you can also unpack the rest, like this:

    >>> a, b, *rest = 1, 2, 3, 4, 5, 6, 7
    >>> a
    1
    >>> rest
    [3, 4, 5, 6, 7]
    

    Unfortunately, this does not work in Python 2 though.

    0 讨论(0)
  • 2020-12-29 02:01

    You could use _ to represent variables you wanted to "throw away"

    >>> a, b, _ = 1, 3, 4
    >>> a
    1
    >>> b
    3
    
    0 讨论(0)
  • 2020-12-29 02:05

    Or in Python 3.x you could do this:

      a, *b = 1, 3, 4
    

    giving you:

    In [15]: a
    Out[15]: 1
    
    In [16]: b
    Out[16]: [3, 4]
    

    It would avoid the exception, though you would have to parse b. This assume that you only want to have two variables on the left of the =, otherwise you could use

    a, b, *ignore = ....
    

    with v3.x

    0 讨论(0)
提交回复
热议问题