将数字字符串作为新元素插入数组中

Inserting string of numbers in an array as new elements

我正在从一个文本文件中读取数字,我总共有 6000 个,它们都在 我的文本文件的最后一行 。我已经想出如何从这个长字符串中创建一个数字列表——即将这个长数字字符串转换为一个大小为 6000 的列表。然而,令人惊讶的是,我的列表大小实际上是 5988。出于某种原因,有些行上有多个数字,即使在我拆分它们之后也是如此。因此,它们看起来像这样:

...
1.79336e-07 # this is arr[0]
1.28945e-07 # .. arr[1]
4.60924e-08
1.52726e-08 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307
-2.62628e-08
-3.19098e-08 # arr[5]
...

这条罕见的线只出现过几次,因此预期大小 6000 和 5988 之间存在差异。

我想将这些行分成各自的编号,并将它们插入到列表中的正确位置..所以将编号更改为:

...
1.79336e-07 # this is arr[0]
1.28945e-07 # .. arr[1]
4.60924e-08
1.52726e-08 
-1.79769e+307 
-1.79769e+307 
-1.79769e+307 
-1.79769e+307 
-1.79769e+307
-2.62628e-08
-3.19098e-08 # arr[10]
...

拆分此行并将它们作为新元素插入列表中以创建更大列表的最佳方法是什么?

这是我目前在我的文件中阅读的方式:

Ux = re.split('  +', list(data_file)[-1])

如果您尝试从文件中读取,您可以创建一个匹配所有用例的正则表达式并将所有结果添加到列表中。

示例字符串输入:

line = """ 
1.79336e-07 # this is arr[0]
1.28945e-07 # .. arr[1]
4.60924e-08
1.52726e-08 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307
-2.62628e-08
-3.19098e-08 # arr[5]
""" 

正则表达式:([-]?\d+.\d+e[-+]?\d+)+,检查 regex101 以了解其工作原理的完整说明。

然后使用:

import re
for match in re.findall('([-]?\d+.\d+e[-+]?\d+)+', line):
    print(match)

将导致:

1.79336e-07
1.28945e-07
4.60924e-08
1.52726e-08
-1.79769e+307
-1.79769e+307
-1.79769e+307
-1.79769e+307
-1.79769e+307
-2.62628e-08
-3.19098e-08

我没有添加任何换行符 ('\n'),但这些会被正则表达式忽略。从文件中读取的完整代码类似于:

data = []
with open('file.txt', 'r') as file:
    for line in file.readlines():
        for match in re.findall('([-+]?\d+.\d+e[-+]?\d+)+', line):
            data.append(match)

我认为最好 post 您的代码,以便我们知道可能导致问题的原因。

如果那些奇数行的数字总是由 space 分隔,这将有效:

for i, a in enumerate(arr):
    if " " in a:
        arr.remove(a)
        for j, b in enumerate(a.split()):
            arr.insert(i+j, b)

在这里,我首先拆分列表的每个元素 ' ' 并展平嵌套列表

listr = ['1.79336e-07', '1.52726e-08 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307 -1.79769e+307']
def flatten(li):
return sum(([x] if not isinstance(x, list) else flatten(x)
            for x in li), [])
newList = []
for i in listr:
    newList.append(i.split(' '))
newList = flatten(newList)
print(newList)