[英]Python - Reading space separated numbers in a string
我有一个使用 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']].
有人可以帮我将每个值附加到列表中吗? 类似输出 =
[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 读取时尝试使用 splitlines() 和 strip('\\n') 但我仍然得到上述格式的值。
先感谢您
我从 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
使用默认在空白处拆分的 split(),而不是查找行尾字符的 splitlines()。 Split 将以字符串形式返回单个数字的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.