[英]too many values to unpack(expected 3)?
I am trying to load some data from a text file, but keep on getting this error:我正在尝试从文本文件中加载一些数据,但不断收到此错误:
def getData(file):
f = open('N_20_T_10.txt','r')
x, y, z = [], [], []
f.readline()
for line in f:
xp, yp, zp = line.split(' ')
x.append(float(xp))
y.append(float(yp))
z.append(float(zp))
f.close()
return x, y, z
def plotData(inputFile):
x, y, z = getData(inputFile)
x = pylab.array(x)
y = pylab.array(y)
z = pylab.array(z)
N = np.linspace(1, 100, 100)
r = np.sqrt(x**2 + y**2+z**2)
mean_r = N*r
data = np.column_stack(N)
data1 = np.column_stack(mean_r)
print(data, mean_r)
#print(N, r)
np.savetxt('new.txt', list(zip(N, mean_r)), fmt='%.1f', delimiter=",")
pylab.plot(N, mean_r)
pylab.xlabel('N')
pylab.show()
plotData('N_20_T_10.txt.txt')
Here is the data I'm using.这是我正在使用的数据。 I think it keeps on coming maybe because of some extra whitespaces in the data, because when I use a different file with no spaces it works well.我认为它不断出现可能是因为数据中有一些额外的空格,因为当我使用没有空格的不同文件时它工作得很好。 But I'm not sure.但我不确定。
From the picture it seems before the first number there is a space.从图片看来,第一个数字之前有一个空格。 Then you will get back 4 elements of the split(' ')
operation.然后你会得到split(' ')
操作的 4 个元素。 See the following example:请参见以下示例:
numbers = " 1 2 3"
numbers.split(' ')
# output: ['','1', '2', '3']
You can solve your problem by skipping the first element of the array as follows:您可以通过跳过数组的第一个元素来解决您的问题,如下所示:
numbers.split(' ')[1:]
# output: ['1', '2', '3']
or using strip()
:或使用strip()
:
numbers.strip().split(' ')
# output: ['1', '2', '3']
or you can simply use split()
without a parameter:或者您可以简单地使用不带参数的split()
:
numbers.split()
# output: ['1', '2', '3']
So in your case, the following code should work:因此,在您的情况下,以下代码应该可以工作:
xp, yp, zp = line.spilt()
I would try to strip all whitespaces at the beginning and the end of each line by using我会尝试使用删除每行开头和结尾的所有空格
xp, yp, zp = line.strip().split(' ')
If this is whitespace problem then you can solve it using split without defining separator.如果这是空白问题,那么您可以使用 split 解决它而不定义分隔符。 Split docs explain:拆分文档解释:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator...如果 sep 未指定或为无,则应用不同的拆分算法:连续空白的运行被视为单个分隔符...
and example和例子
>>> ' 1 2 3 '.split()
['1', '2', '3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.