将数字列表解析为 python 中的列表

Parse list of numbers into list in python

我有一个包含以下格式数字的文本文件:

 {5.2, 7.3}
 {1.4, 6.2}

我想将它们加载到具有两列且行数与文件中的条目相同的浮点数列表中,像这样 [[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。像这样:

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

我可以用 [ 和 ] 替换 { 和 },然后尝试将其转换为列表吗?

您可以做一些简单的字符串替换,然后使用 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 以在正确的位置使用逗号:

with open('somefile.txt') as f:
    data = ','.join(line.replace('{','[').replace('}',']')
        for line in f if line.strip())
    return ast.literal_eval(data)

另一种方法怎么样,它不使用替换和求值(有些冒险),而是使用正则表达式。不过,它确实违反了您的 "no for loop" 规则:

>>> import re
>>> [[float(i) for i in re.findall(r'(\d\.?\d?)', z)] for z in open('foo.txt').readlines() if len(z.strip())]
[[5.2, 7.3], [1.4, 6.2]]