Python:如何将包含行列格式坐标的文本文件读入 xy 坐标数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20735922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: How to read a text file containing co-ordinates in row-column format into x-y co-ordinate arrays?
提问by AnchalAgrawal
I have a text file with numbers stored in the following format:
我有一个文本文件,其中的数字以以下格式存储:
1.2378 4.5645
6.789 9.01234
123.43434 -121.0212
... and so on.
... 等等。
I wish to read these values into two arrays, one for x co-ordinates and the other for y co-ordinates. Like, so
我希望将这些值读入两个数组,一个用于 x 坐标,另一个用于 y 坐标。喜欢,所以
x[0] = 1.2378
y[0] = 4.5645
x[1] = 6.789
y[1] = 9.01234
... and so on.
... 等等。
How should I go about reading the text file and storing values?
我应该如何阅读文本文件并存储值?
采纳答案by Thayne
One method:
一种方法:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
where f is the file object (from open() for instance)
其中 f 是文件对象(例如来自 open() )
You could also use the csv library
您还可以使用 csv 库
import csv
with open('filename','r') as f:
reader = csv.reader(f,delimeter=' ')
for row in reader:
x.append(row[0])
y.append(row[1])
And you can also use zip to make it more succinct (though possibly less readable:
您还可以使用 zip 使其更简洁(尽管可能不太可读:
x,y = zip(*[l.split() for l in f])
where f is the file object, or
其中 f 是文件对象,或
import csv
x,y = zip(*csv.reader(f,delimeter=' '))
again where f is the file object. Not that the last two methods will load the entire file into memory (although if you are using python 3 you can use generator expressions and avoid that).
再次,其中 f 是文件对象。并不是说最后两种方法会将整个文件加载到内存中(尽管如果您使用的是 python 3,您可以使用生成器表达式并避免这种情况)。
回答by aIKid
Read it per lines, and split it using split:
每行读取它,并使用split以下方法拆分:
with open('f.txt') as f:
for line in f:
x, y = line.split()
#do something meaningful with x and y
Or if you don't mind with storing the whole list to your computer's memory:
或者,如果您不介意将整个列表存储到计算机内存中:
with open('f.txt') as f:
coordinates = [(c for c in line.split()) for line in f]
And if you want to store the xs and ys in separate variables:
如果您想将xs 和ys存储在单独的变量中:
xes = []
ys = []
with open('f.txt') as f:
for line in f:
x, y = line.split()
xes.append(x)
ys.append(y)

