python - 要列出的坐标 (str)

标签 python python-2.7 python-3.x

我有一个很长的包含地理坐标的 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)

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

最佳答案

除了简单地拆分每一行并强制转换为 float 之外,您不需要 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()

关于python - 要列出的坐标 (str),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28251866/

相关文章:

json - Azure 认知服务 : Face Find Similar 'BadArgument' , 'Argument faceListId and faceIds cannot be provided at the same time.' 。'

当我尝试保存带有特定注释的文件时,Python IDLE 拒绝保存并且崩溃

python - 如何在 Python 中使用 PhantomJS 清除 Selenium 中的缓存和 cookie?

python-2.7 - 使用python查找数据框中序列重复的次数

python - 在 Python Anywhere 托管服务器中触发 OpenCV 脚本时找不到相机

python - 如何避免大写首字母缩略词被.capitalize() 小写? Python

python - 从 Haskell 调用 Sage

python - 如何使用 Streamlit 单击按钮切换页面?

python - 子任务会继承父任务的队列吗?

python - boto3.client ('S3' ) 返回什么?