将数字列表解析为python中的列表 [英] Parse list of numbers into list in python
问题描述
我有一个包含以下格式数字的文本文件:
I have a text file containing numbers in the following format:
{5.2, 7.3}
{1.4, 6.2}
我想将它们加载到具有两列且行数与文件中条目相同的浮点列表中,例如 [[5.2,7.3],[1.4,6.2],...]
I would like to load these into a list of floats with two columns and the same number of rows as entries in the file, like this [[5.2, 7.3], [1.4, 6.2], ...]
目前我正在这样做:
f = open(filename,'r')
mylist = []
for line in f:
strippedLine = line.strip('{}\n')
splitLine = strippedLine.split(',')
a=float(splitLine[0])
b=float(splitLine[1])
ab=np.array([a,b])
mylist.append(ab)
f.close()
这很好用,但是我想摆脱for循环,即只使用split,strip和float.像这样:
This works fine, but I would like to get rid of the for-loop, i.e. only use split, strip and float. Something like this:
f = open(filename,'r')
lines = f.read()
f.close
split_lines = lines.split('\n')
# Then something more here to get rid of { and }, and to rearrange into the shape I want
我可以将{和}替换为[和],然后尝试将其转换为列表吗?
Could I maybe replace { and } with [ and ], and then try to convert it into a list?
推荐答案
您可以进行一些简单的字符串替换,然后使用 ast.literal_eval
:
You can do some simple string replacements and then use ast.literal_eval
:
>>> data = "{5.2, 7.3}\n{1.4, 6.2}\n"
>>> import ast
>>> ast.literal_eval(data.replace('{','[').replace('}',']').replace('\n',','))
([5.2, 7.3], [1.4, 6.2])
>>>
或者在文件上使用str.join将逗号放在正确的位置:
Alternatively use str.join on the file to get the commas in the right place:
with open('somefile.txt') as f:
data = ','.join(line.replace('{','[').replace('}',']')
for line in f if line.strip())
return ast.literal_eval(data)
这篇关于将数字列表解析为python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!