在python中从xml读取列表中的数据
我得到的输出是在python中从xml读取列表中的数据,python,Python,我得到的输出是['-2,-2,-2,-2','-2,-2,-1,-2,-2','-2,-2,-1,-2'] 但是我需要输出为[[-2,-2,-2,-2,-2],-2,-1,-2,-2],-2,-2,-1,-2]。试试这个: Ints = [] for child in root.findall('randomints'): Ints = [l.text for l in child] 输出: import xml.etree.ElementTree as ET root = ET.p
['-2,-2,-2,-2','-2,-2,-1,-2,-2','-2,-2,-1,-2']
但是我需要输出为[[-2,-2,-2,-2,-2],-2,-1,-2,-2],-2,-2,-1,-2]。
试试这个:
Ints = []
for child in root.findall('randomints'):
Ints = [l.text for l in child]
输出:
import xml.etree.ElementTree as ET
root = ET.parse("infile.xml")
for child in root.findall('randomints'):
ints = [list(map(int, l.text.split(","))) for l in child]
print(ints)
您可以尝试这样做:
Ints=[[int(el)表示l.text中的el.split(',')]表示l在child中]
。最终,您只需要对所获得的l.text
进行一些处理。请记住,对非数字/整数类对象调用int
会引发ValueError
,我发现ElementTree.parse
不会将xml作为
加载,而必须是
。。。
import xml.etree.ElementTree as ET
root = ET.parse("infile.xml")
for child in root.findall('randomints'):
ints = [list(map(int, l.text.split(","))) for l in child]
print(ints)
[[-2, -2, -2, -2, -2], [-2, -2, -1, -2, -2], [-2, -2, -2, -1, -2]]