2

i have a list of values that i got when reading an xml file using etree:

[['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.

Thank you in advance

I have added a snippet from an xml and my code:

<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

sat0408
  • 73
  • 12
  • Can you post some sample code, as well as what you're getting? – Deacon Mar 10 '16 at 17:12
  • Hello Doug! I have updated the question with my code. – sat0408 Mar 11 '16 at 08:58
  • Thanks. For clarification: "My aim is to have every single number into a list." Do you mean every number into its own list, or every line in a list? – Deacon Mar 11 '16 at 11:51
  • I meant a list with all numbers. I solved it in the meantime:) . I added an extra function for achieving my objective (Edited my original Post). Not sure if there is any other smarter alternative – sat0408 Mar 11 '16 at 14:28
  • Congratulations! You should actually post your answer **as an answer** and then accept it, once you're able to. That will help the next person find this as a solved question. – Deacon Mar 11 '16 at 14:35

2 Answers2

1

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
sat0408
  • 73
  • 12
  • I would suggest that you also explain what you did and why it worked for you. Again - think of the next person. Write the answer that you would've wanted to get. – Deacon Mar 11 '16 at 15:08
0

Use split() which splits at whitespace by default, instead of splitlines() which looks for end-of-line characters. Split will return a list of the individual numbers as strings.

Steve
  • 976
  • 5
  • 15