将字符串列表拆分为浮点数 - 内存错误

Spliting a string list to floats - memory error

我无法处理将字符串列表拆分为浮点数列表的问题。我打开一个文本文件(.vol,但它只包含文本),最后一行是一长串数字。

Params1 437288.59375000 102574.20312500 -83.30001831
Params2 437871.93750000 104981.40625000 362.10000610
Params3 0.00000000
Params4 342 1416 262
Params5 583.34375000 2407.19995117 445.40002441
Params6 20.00000000
Params7 1.70000005
Params8 126879264
Values:
0.25564435 0.462439 0.1365 0.1367 26.00000000 (etc., there are millions of values)

因为它是 txt 文件的第 10 行,我通过以下方式将它们加载到列表中:

with open('d:/py/LAS21_test.vol') as f:
txt = []
for line in f:
    txt.append(line)

然后我尝试通过以下方式将其从字符串转换为浮点数:

A = []
for vx in txt[9]:
   try:
       A.append(float(vx))
   except ValueError:
       pass
print (A[0:20])
print (txt[9][0:20])

这给我结果:

[0.0, 2.0, 5.0, 5.0, 6.0, 4.0, 4.0, 3.0, 5.0, 0.0, 4.0, 6.0, 2.0, 4.0, 3.0, 9.0, 0.0, 1.0, 3.0, 6.0]
0.25564435 0.462439 

我想要的是正确拆分的浮点数列表,例如:

[0.25564435, 0.462439]

我使用 except ValueError 来省略空格 - 当只使用 float(txt[9]) 时我得到值错误。 第二个问题:我不能使用 txt[9].split,因为那样我会得到 'memory error'。

如何将其正确转换为浮点数列表?

您的问题(如评论中所述)是:

1) 在第一种情况下,您试图在拆分字符串之前对其进行索引,并且您试图将空格转换为浮点数(因此 ValueError

2) 在第二种情况下,列表中的数字可能太多,您正在用大量大字符串列表(因此 MemoryError)填满您的记忆。

先试试这个:

numbers = [float(s) for s in txt[9].split(' ')]

这应该会为您提供一个数字列表。如果这也导致 MemoryError,您将不得不手动遍历字符串:

numbers = []
numstring = []
for s in txt[9]
    # Reached a space
    if s == ' ':
        numbers.append(float(numstring))
        numstring = []
    else:
        numstring.append(s)

这会慢很多,但会节省内存。

如果我理解正确的话,你不能制作 txt[9].split() 并像这样映射它:map(float, txt[9].split()) 因为 txt[9] 太大了。

你可以试试这个生成器:

def float_generator(txt):
        x = ''
        for c in txt:
            if c != ' ':
                x += c
            else:
                out = float(x)
                x = ''
                yield(out)

for i in float_generator(txt[9]):
        print (i)