简体   繁体   中英

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. 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() :

numbers.strip().split(' ')
# output: ['1', '2', '3']

or you can simply use split() without a parameter:

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 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...

and example

>>> '   1   2   3   '.split()
['1', '2', '3']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM