我怎样才能读取我的文件行中的每一行作为浮动列表? [英] How can I read in my file line by line with each line as a list of floats?
问题描述
[ - 74.0104294,40.6996416] $ b我有一个文件,每行有一对坐标$ b
我正在使用的代码是:
with open('Manhattan_Coords.txt','r')as f:
mVerts = f.read()。splitlines()
这将所有78行读入一个列表,但是它以字符串的形式读取它们,所以当我将它们打印出来时, :
['[( - 74.0104294,40.6996416]',...,'[-74.0104294,40.6996416]' ]
(想象一下,如第一个和最后一个76个坐标)
如何将每个坐标对读作列表,以便我在每个子列表中留下一个包含2个浮点数的78个子列表?
对于每一行,您需要:
$ b $ ol
...使用
作为
lo我们可以遍历文件 使用 str.strip()来删除包含换行符的空白
... using 字符串切片:
[1:-1]
','
...使用
str.split )
和列表理解 。...使用
float()$ c $
将每对浮点数添加到列表中
...使用 list.append()
看起来像这样: $ f $ b $
$ m
$ s()[1:-1] .split(,)]
m_verts.append(pair)
之后, m_verts
如下所示:
>>> m_verts
[[-74.0104294,40.6996416],...]
最好是迭代一个文件的行,而不是像 I have a file where each line has a pair of coordinates like so: The code that I'm using to read them in is: This reads in all 78 lines into a list, but it reads them in as strings, so when I print them out it shows up as: (Imagine the ... as 76 more coordinates like the first and last) How can I read in each of these coordinate pairs as a list so that I am left with a list of 78 sublists with 2 floats inside each sublist? For each line, you need to: That looks like this: After which, In general, you're better off iterating over the lines of a file than reading them all into a list at once with methods like Also, notice that I've used the more pythonic under_score style to name 这篇关于我怎样才能读取我的文件行中的每一行作为浮动列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! splitlines()
这样的方法将它们全部读入列表中。它更具可读性,并且具有大文件另外,请注意,我已经使用了pythonic under_score 风格来命名 m_verts code>,而不是你的 camelCase 风格,打开一个文件读取时不需要指定
'r'
。 / p> [-74.0104294, 40.6996416]
with open('Manhattan_Coords.txt', 'r') as f:
mVerts = f.read().splitlines()
['[(-74.0104294, 40.6996416]', ... , '[-74.0104294, 40.6996416]']
... using a for
loop to iterate over the file
... using str.strip()
... using string slicing: [1:-1]
', '
... using str.split()
and a list comprehension.
... using float()
... using list.append()
m_verts = []
with open('Manhattan_Coords.txt') as f:
for line in f:
pair = [float(s) for s in line.strip()[1:-1].split(", ")]
m_verts.append(pair)
m_verts
looks like this:>>> m_verts
[[-74.0104294, 40.6996416], ... ]
splitlines()
... it's more readable, and with large files much more efficient.m_verts
, rather than your camelCase style - and that there's no need to specify 'r'
when opening a file for reading.