如何在 Python 中修复 ValueError: Too many values to unpack”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17403371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:06:57  来源:igfitidea点击:

How can I fix ValueError: Too many values to unpack" in Python?

pythonpython-3.x

提问by Poker Face

I am trying to populate a dictionary with the contents of my text file ("out3.txt").

我试图用我的文本文件(“out3.txt”)的内容填充字典。

My text file is of the form:

我的文本文件的格式如下:

vs,14100

mln,11491

the,7973

cts,7757

...and so on...

...等等...

I want my dictionary answerto be of the form:

我希望我的字典answer采用以下形式:

answer[vs]=14100

answer[mln]=11491

...and so on...

...等等...

My code is:

我的代码是:

import os
import collections
import re
from collections import defaultdict

answer = {}
answer=collections.defaultdict(list)
with open('out3.txt', 'r+') as istream:
    for line in istream.readlines():
        k,v = line.strip().split(',')
        answer[k.strip()].append( v.strip())

But, I get:

但是,我得到:

ValueError: too many values to unpack

值错误:解包的值太多

How can I fix this?

我怎样才能解决这个问题?

采纳答案by Johnsyweb

You have empty lines in your input file and I suspect one of the lines that you have not shared with us has too many commas in it (hence "too many values to unpack").

line的输入文件中有空s,我怀疑line您未与我们共享的s之一中包含太多逗号(因此“解包的值太多”)。

You can protect against this, like so:

您可以防止这种情况,如下所示:

import collections

answer = collections.defaultdict(list)
with open('out3.txt', 'r+') as istream:
    for line in istream:
        line = line.strip()
        try:
            k, v = line.split(',', 1)
            answer[k.strip()].append(v.strip())
        except ValueError:
            print('Ignoring: malformed line: "{}"'.format(line))

print(answer)

Note:By passing 1into str.split(), everything after the first comma will be assigned to v; if this is not desired behaviour and you'd prefer these lines to be rejected, you can remove this argument.

注:通过传递1str.split(),一切后,第一个逗号将被分配到v; 如果这不是您想要的行为并且您希望拒绝这些行,您可以删除此参数。

回答by Burhan Khalid

Your solution doesn't give your desired output. You'll have (assuming it worked), answer['vs'] = [14100], the below does what you intended:

您的解决方案没有提供您想要的输出。您将拥有(假设它有效),answer['vs'] = [14100]以下内容符合您的意图:

import csv

with open('out3.txt') as f:
  reader = csv.reader(f, delimiter=',')
  answer = {line[0].strip():line[1].strip() for line in reader if line}

回答by pepr

You do not need the collectionshere. Plain old dict is enough:

你不需要collections这里。普通的旧字典就足够了:

answer = {}
with open('out3.txt', 'r+') as f:
    for line in f:
        lst = line.split(',')
        if len(lst) == 2:
            k = lst[0].strip()
            v = lst[1].strip()
            answer[k] = v

print(answer['mln'])
print(answer.get('xxx', 'not available'))

Notice the answer.get()is similar to answer[]but you can supply the defaul value.

请注意,answer.get()类似于answer[]但您可以提供默认值。

You should not use .readlines()in the loop. Even the empty line contains the newline character. This way the test if line:does not detects the empty lines. Or you have to strip (or rstrip) it first, or you can split the line to the list and test the number of elements.

你不应该.readlines()在循环中使用。即使是空行也包含换行符。这样测试if line:就不会检测到空行。或者您必须先剥离(或rstrip)它,或者您可以将行拆分为列表并测试元素数。