Skip to main content
 首页 » 编程设计

Python之读取字符串中的空格分隔数字

2025年05月04日12mfrbuaa

我有一个使用 etree 读取 xml 文件时得到的值列表:

[['0'] 
['0 1.56E-013 2.22E-014 0 0 0'] 
['-2.84E-014 1.42E-014 2.56E-015  0 0 0'] 
['0 0 0 0 0 0'] 
['0 0 0 0 0 0']]. 

有人可以帮我将每个值附加到列表中吗? 类似 output =

[0,0,1.56E-013,2.22E-014,0,0,0,-2.84E-014,1.42E-014,2.56E-015,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 

我尝试在从 xml 和 strip('\n') 读取时使用 splitlines(),但我仍然得到上述格式的值。

提前致谢

我从 xml 和我的代码中添加了一个片段:

<Data name="IC_001" id="2"> 
<Step type="IC"> 
0 
0 1.56E-013 2.22E-014 0 0 0 
-2.84E-014 1.42E-014 2.56E-015 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 
</Step> 
</Data> 

我的代码:

import xml.etree.ElementTree as ET 
tree = ET.parse('test2.xml') 
root = tree.getroot() 
temp = root.findall("./Step") 
for item in temp: 
    values = item.text.strip('\n').splitlines() 
print values 

我的目标是将每个数字都放入一个列表中。 我真的很感激任何帮助

请您参考如下方法:

已解决:

import xml.etree.ElementTree as ET 
def test(): 
    tree = ET.parse('test2.xml') 
    root = tree.getroot() 
    temp = root.findall("./Step") 
    for item in temp: 
        values = item.text.strip('\n').splitlines() 
    values_out = process_step_data(values) 
    print values_out 
 
def process_step_data(output_step): 
    step_result = [] 
    for i in range(len(output_step)): 
        for num_str in output_step[i].splitlines(): 
            x = [float(j) for j in num_str.split()] 
            step_result = step_result + x 
    return step_result