python - 从文件中读取连续的三列到数组中

标签 python python-3.x function

我正在编写一个关于从文本文件中读取 3D 坐标并将其传递到数组中的基本 Python 程序。 这是我的文本文件的一部分。

1              0.20069808    0.70680627    0.00000000
2              1.66069808    0.70680627    0.00000000
3              0.20069808    2.16680627    0.00000000
...

我自己一直在尝试,以下是我的实验

coord_raw = []
x = []
y = []
z = []

for line in f:
    lst = line.split()
    print(lst[1])
    x.append(lst[1])
    y.append(lst[2])
    z.append(lst[3])
    coord_raw.append((x, y, z))

    #coord_raw += [x, y, z]

我期望的是以下内容

[[0.20069808,0.70680627,0.00000000]
 [1.66069808,0.70680627,0.00000000]
 [0.20069808,2.16680627,0.00000000]
 ...                           ...]
 ...                           ...]]

但是,它显示错误

     x.append(lst[1])
IndexError: list index out of range

任何人都可以帮助我解决这个问题并评论我如何使我的代码更容易和更快吗?
我很感激任何帮助。

最佳答案

我认为你应该考虑使用 numpy:

import numpy as np    
arr = np.loadtxt(filepath)
np.delete(arr, 0, 1) # deletes the first column of 0, 1, 2, 3

因为 numpy 数组将更容易处理数字数据

关于python - 从文件中读取连续的三列到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985063/

相关文章:

python - 我有一个 int 123。如何使用 python 生成字符串 "100+20+3"?

python - 通过异步 websocket 客户端与 websocket 服务器保持连接

python - 无法通过子进程执行 msg(和其他)Windows 命令

python - GPU 处理 - cuDF 安装问题(O/S 或硬件问题?)

python - 如何克服Python中的 "classmethod is not callable"

python - 与 mysql 的连接速度极慢

function - QEMU 中的 USB 功能 Controller 仿真

sql - 反向连接 - 分割函数

python - 如何更有效地求平方和?

python - Pandas :合并两个数据框并保留来自单个数据框的非交叉数据