" ValueError:需要多于1个值来解包"

时间:2015-06-09 14:29:22

标签: python

highest_score = 0
result_f = open("gp.txt")
for line in result_f:
    (name, number) = line.split()
    if float(number) > highest_score :
        highest_score = float(number)
result_f.close()
print("The highest score was:")
print(highest_score)

运行此代码时出现的错误是:

Traceback (most recent call last):
  File "/Users/APPLE/Desktop/gp.py", line 4, in <module>
    (name, number) = line.split()
ValueError: need more than 1 value to unpack

出了什么问题?

  

链接到屏幕截图:http://www.tiikoni.com/tis/view/?id=263b001

编辑:根据链接显示的内容,gp.txt应包含:

Johnny  8.65
Juan  9.12
Joseph  8.45
Stacey  7.81
Aideen  8.05
Zack  7.21
Aaron  8.31

3 个答案:

答案 0 :(得分:0)

如果没有更多信息,我猜想当line.split()处理问题输入行时(#4根据您的错误消息),结果只有一个值。交互式会话的简单演示显示了类似的结果:

>>> line = 'abc'
>>> line.split()
['abc']
>>> a,b = line.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

因此,要么清理输入文件,要么在处理时检查线条是否正确分隔。

在编辑问题后编辑:

正如我在上面的评论中所说,我复制并粘贴了您的程序并创建了一个看起来像您显示的数据文件的文件。该程序运行,没有产生任何错误,并声明:

  

得分最高的是:
  9.12

我怀疑您在链接中显示的文件在进行一些编辑后未保存,并且您的程序正在处理存储在硬盘驱动器上的文件的早期版本。保存您正在显示的文件版本,然后再次尝试您的程序。

答案 1 :(得分:0)

由于某种原因,文件gp.txt中的一行未按预期分割,因此分割的返回是一个带有字符串的列表。一种告诉你哪条线是违规线的方法 - 以及一般的良好做法 - 是检查split是否产生了你期望的线:

# first do the splitting, but don't make any assumptions
# about the result just yet
tokenized = line.split()

# Check that the split has gone according to plan. If not, 
# print (log would be better) a message and the line, and 
# continue to next line
if len(tokenized) != 2:
    print "Found malformed line: {}".format(line)
    continue

# Now you can safely unpack
(name, number) = tokenized

它有点冗长,但它更安全,会告诉你问题所在。您还可以在enumerate循环中使用for来启用行号的打印。我想知道问题是否因为存在最终换行符或类似问题而发生。

答案 2 :(得分:0)

谢谢大家,但我自己解决了这个问题。问题是macos的textedit应用程序。我安装了原子texteditor,然后在其中写了名称和数字,并将其保存为txt ...这次当我使用这个文件而不是jsing那个textedit时它起作用了。也许texedit一个人隐藏了一些线条或者有些东西。但这很有用。