要列出的坐标 (str)

coordinates (str) to list

我有一个很长的包含地理坐标的 txt 文件。每行的格式如下所示:

501418.209 5314160.484 512.216
501418.215 5314160.471 512.186
501418.188 5314160.513 512.216

所以用空格 (" ") 分隔,最后换行 (\n)

我需要将该文件导入到列表中...到目前为止,我只能设法将其作为字符串导入,然后尝试将其转换为列表。不幸的是,我不知道如何保持 txt 文件的格式,因为我需要对每一行执行计算。

我目前将 txt 文件导入字符串变量的解决方案:

fileobj = file(source,'r')
data = ""
for line in fileobj.readlines():
    linevals = line.strip().split(" ")
    data += "%s %s %s\n" % (linevals[0], linevals[1], linevals[2])
print type(data)

我的导入为列表的解决方案无效:

fileobj = file(source,'r')
data = []
for line in fileobj.readlines():
    linevals = line.strip().split(" ")
    data.append(linevals)

在 Whosebug 上,我发现了很多建议使用 eval 函数的解决方案 - 但它不起作用,因为我需要将整行作为一个列表元素。希望那是清楚的。这个问题有什么解决办法吗?我对 python 很陌生,但这困扰了我很长一段时间。谢谢!

除了简单地拆分每一行并强制转换为浮动之外,您不需要 eval 或其他任何东西:

with open(source) as f:
    for row in f:
        print(map(float,row.split()))

[501418.209, 5314160.484, 512.216]
[501418.215, 5314160.471, 512.186]
[501418.188, 5314160.513, 512.216]

如果您希望所有行都在一个列表中:

with open(source) as f:
    data = [ map(float,row.split()) for row in f] #  python3 ->list(map(float,row.split()))
    print(data)
[[501418.209, 5314160.484, 512.216], [501418.215, 5314160.471, 512.186], [501418.188, 5314160.513, 512.216]]

或使用 csv 模块:

import  csv
with open(source) as f:
    data = [map(float,row) for row in csv.reader(f,delimiter=" ")]
    print(data)

如果您想要所有数据的平面列表:

with open(source) as f:
   data = []
   for row in f:
       data.extend(map(float,row.split())) 

如果您在数据上做了大量工作,您可能会发现 numpy 很有用:

import numpy as np

data = np.genfromtxt(source,delimiter=" ").flatten()