简体   繁体   English

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

[英]Python - Reading space separated numbers in a string

i have a list of values that i got when reading an xml file using etree:我有一个使用 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']].

Could someone help me out to append every single values to a list?有人可以帮我将每个值附加到列表中吗? Something like 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]

I tried using splitlines() when reading from xml and also strip('\\n') but i still get the values in the above format.我在从 xml 读取时尝试使用 splitlines() 和 strip('\\n') 但我仍然得到上述格式的值。

Thank you in advance先感谢您

I have added a snippet from an xml and my code:我从 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>

My code:我的代码:

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

My aim is to have every single number into a list.我的目标是将每个数字都放入一个列表中。 I would really appreciate any help我真的很感激任何帮助

Solved:解决了:

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

Use split() which splits at whitespace by default, instead of splitlines() which looks for end-of-line characters.使用默认在空白处拆分的 split(),而不是查找行尾字符的 splitlines()。 Split will return a list of the individual numbers as strings. Split 将以字符串形式返回单个数字的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM