繁体   English   中英

通过垂直拆分文本文件创建列表

[英]Creating lists from a text file by splitting it vertically

我想使用 Python 将此文本文件分成 3 个(称为xye )列表,但我似乎做不到。

这是文本文件(称为数据)的样子:

x y e
-2 2.1 0.170358869161
0 2.4  0.170202773308
2 2.5  -0.138557648063
4 3.5  0.187965696415
6 4.2  -0.473073365465

这是我目前无法使用的代码:

x=[]
y=[]
e=[]

try: 
    data = open('data.txt', 'rt')
except:
    sys.exit('cannot find file')

with data:    
    try:
        x.append(data[:1])
        y.append(data[2:3])
        e.append(data[4:5])
except:
    sys.exit('cannot create lists')

做这个:

with data as f:     # f is the file object
    for line in f:  # you can iterate over a file object line-by-line
        xi, yi, ei = line.split()
        x.append(xi)
        y.append(yi)
        e.append(ei.strip()) # ei will have a \n on the end

如果你对它们的形状的假设是正确的,你可以在追加它们时将它们强制为int或浮动。

如果你有熊猫,我推荐read_csv

>>> import pandas as pd
>>> pd.read_csv('data.txt', delim_whitespace=True)
   x    y         e
0 -2  2.1  0.170359
1  0  2.4  0.170203
2  2  2.5 -0.138558
3  4  3.5  0.187966
4  6  4.2 -0.473073

你可以使用csv lib:

import csv

x, y, e = [], [], []
with open("in.csv") as f:
    next(f)
 for a, b, c in csv.reader(f, delimiter=" ", skipinitialspace=1):
    x.append(float(a))
    y.append(float(b))
    e.append(float(c))

输出:

[-2.0, 0.0, 2.0, 4.0, 6.0]
[2.1, 2.4, 2.5, 3.5, 4.2]
[0.170358869161, 0.170202773308, -0.138557648063, 0.187965696415, -0.473073365465]

或者使用defaultdict对元素进行分组:

import csv
from collections import defaultdict


with open("in.csv") as f:
    d = defaultdict(list)
    for dct in csv.DictReader(f, delimiter=" ", skipinitialspace=1):
        for k, v in dct.items():
            d[k].append(float(v))

from pprint import  pprint as pp

pp(dict(d))

输出:

{'e': [0.170358869161,
       0.170202773308,
       -0.138557648063,
       0.187965696415,
       -0.473073365465],
 'x': [-2.0, 0.0, 2.0, 4.0, 6.0],
 'y': [2.1, 2.4, 2.5, 3.5, 4.2]}

我看到上面的回复有使用硬编码变量的答案。 但是我找到了一种方法来创建可以容纳无限行的列表。

def getFrom(index: int, data: list):
    returnList = []
    for item in data:
        if len(item) >= index:
            returnList.append(item[index])
        else:
            returnList.append("")
    return returnList

在这个function中,data是你要查找的列表,可以嵌套,index是你要查找的索引。 这将返回一个列表,其中包含垂直空间索引中的内容。

你也可以试试

data = ...
endList = [getFrom(index, data) for index in range(len(data))]

和 endList 如果数组垂直拆分的结果。

暂无
暂无

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

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