ValueError: need more than 1 value to unpack python

后端 未结 4 1340
抹茶落季
抹茶落季 2020-12-06 18:01

I have got an existing menu that gives you options L or D. L should load the contents of a file and D should display it.<

相关标签:
4条回答
  • 2020-12-06 18:24

    If you want to work around that without adding extra lines and checks, one solution is to change your split to the following:

    name, adult, child, garbage = (line+',,,').split(',', maxsplit=3)
    

    This will silently ignore the missing values, and the variables will be empty. Meaning, the values for name, adult and child will be filled if they are there, and will be empty it the original file doesn't have them. For all intents and purposes, ignore the variable garbage.

    0 讨论(0)
  • 2020-12-06 18:29

    This means that there is a line in packages.txt that, when you strip whitespace and split on commas, doesn't give exactly three pieces. In fact, it seems that it gives only 1 piece ("need more than 1 value to unpack"), which suggests that there's a line with no commas at all.

    Perhaps there are blank or comment lines in packages.txt?

    You may need your code to be smarter about parsing the contents of the file.

    0 讨论(0)
  • 2020-12-06 18:31

    line.split(',') returns a tuple. You then un-pack that tuple by writing:

    name,adult,child= line.split(',')
    

    If the tuple does not have exactly three elements then the un-packing fails. In your case the error message states that you have only one element. So, line.split(',') is clearly returning a tuple with only one element. And that means that line has no commas.

    Probably this means that your input data is not what you expect it to be. You require that line is a string containing three comma separated values but there is a line in your input data that does not meet that requirement.

    0 讨论(0)
  • 2020-12-06 18:44

    This error is occurring at

    name,adult,child= line.split(',')
    

    When you assign three variables on the left it is assuming you have a 3-tuple on the right. In this example, it appears line has no comma hence line.split(',') results in a list with only one string, thus the error "more than 1 value to unpack".

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