简体   繁体   English

将文件元素读取到3个不同的数组中

[英]Read file elements into 3 different arrays

I have a file that is space delimited with values for x,y,x. 我有一个用x,y,x值分隔的文件。 I need to visualise the data so I guess I need so read the file into 3 separate arrays (X,Y,Z) and then plot them. 我需要可视化数据,所以我想我需要将文件读取为3个单独的数组(X,Y,Z),然后进行绘制。 How do I read the file into 3 seperate arrays I have this so far which removes the white space element at the end of every line. 到目前为止,我如何将文件读取为3个单独的数组,该数组将删除每行末尾的空白元素。

def fread(f=None):
    """Reads in test and training CSVs."""
    X = []
    Y = []
    Z = []

    if (f==None):
        print("No file given to read, exiting...")
        sys.exit(1)

    read = csv.reader(open(f,'r'),delimiter = ' ')
    for line in read:
        line = line[:-1]

I tried to add something like: 我试图添加类似的东西:

for x,y,z in line:
    X.append(x)
    Y.append(y)
    Z.append(z)

But I get an error like "ValueError: too many values to unpack" 但我收到类似“ ValueError:太多值以至无法解包”的错误

I have done lots of googling but nothing seems to address having to read in a file into a separate array every element. 我做了很多谷歌搜索,但是似乎没有什么需要解决的是必须将文件中的每个元素读入一个单独的数组中。

I should add my data isn't sorted nicely into rows/columns it just looks like this "107745590026 2 0.02934046648 0.01023879368 3.331810236 2 0.02727724425 0.07867902517 3.319272757 2 0.01784882881"...... 我应该添加我的数据不是很好地按行/列排序,它看起来像这样“ 107745590026 2 0.02934046648 0.01023879368 3.331810236 2 0.02727724425 0.07867902517 3.319272757 2 0.01784882881” ......

Thanks! 谢谢!

EDIT : If your data isn't actually separated into 3-element lines (and is instead one long space-separated list of values), you could use python list slicing with stride to make this easier: 编辑 :如果您的数据实际上没有分成3个元素的行(而是一个长的空格分隔的值列表),则可以使用带有跨步的python列表切片来简化此操作:

X = read[::3]
Y = read[1::3]
Z = read[2::3]

This error might be happening because some of the lines in read contain more than three space-separated values. 由于read某些行包含三个以上以空格分隔的值,因此可能会发生此错误。 It's unclear from your question exactly what you'd want to do in these cases. 从您的问题尚不清楚,在这些情况下您想做什么。 If you're using python 3, you could put the first element of a line into X , the second into Y , and all the rest of that line into Z with the following: 如果您使用的是python 3,则可以使用以下命令将一行的第一个元素放入X ,第二个放入Y ,并将该行的其余所有放入Z

for x, y, *z in line:
    X.append(x)
    Y.append(y)
    for elem in z:
        Z.append(elem)

If you're not using python 3, you can perform the same basic logic in a slightly more verbose way: 如果您不使用python 3,则可以以更详细的方式执行相同的基本逻辑:

for i, elem in line:
    if i == 0:
        X.append(elem)
    elif i == 1:
        Y.append(elem)
    else:
        Z.append(elem)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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