ValueError: too many values to unpack - Is it possible to ignore one value?

前端 未结 4 1412
夕颜
夕颜 2020-12-20 19:34

The following line returns an error:

self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile         


        
相关标签:
4条回答
  • 2020-12-20 20:01

    You can use *rest from Python 3.

    >>> x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7
    >>> x
    1
    >>> y
    2
    >>> rest
    [4, 5, 6, 7]
    

    This way you can always be sure to not encounter unpacking issues.

    0 讨论(0)
  • 2020-12-20 20:17

    Just, use the throw-away variable '_'

      self.m, 
      self.userCodeToUserNameList, 
      self.itemsList, 
      self.userToKeyHash, 
      self.fileToKeyHash, 
      _ = readUserFileMatrixFromFile(x,True)
    

    here '_' is deliberately ignored.

    0 讨论(0)
  • 2020-12-20 20:20

    Just slice the last one out:

    self.m,  self.userCodeToUserNameList, \
    self.itemsList, self.userToKeyHash, \
    self.fileToKeyHash = readUserFileMatrixFromFile(x,True)[:-1]
    

    EDIT after TigerhawkT3's comment :

    Note that this works only if the return object supports slicing.

    0 讨论(0)
  • 2020-12-20 20:22

    It's common to use _ to denote unneeded variables.

    a, b, c, d, e, _ = my_func_that_gives_6_values()
    

    This is also often used when iterating a certain number of times.

    [random.random() for _ in range(10)]  # gives 10 random values
    

    Python 3 also introduced the * for assignment, similar to how *args takes an arbitrary number of parameters. To ignore an arbitrary number of arguments, just assign them to *_:

    a, b, c, d, e, *_ = my_func_that_gives_5_or_more_values()
    

    This can be used at any point in your assignment; you can fetch the first and last values and ignore padding in the middle:

    >>> a, b, c, *_, x, y, z = range(10)
    >>> print(a, b, c, '...', x, y, z)
    0 1 2 ... 7 8 9
    
    0 讨论(0)
提交回复
热议问题