我有 XMl模拟输出,有许多vehicle
行,如:
<routes>
<vehicle id="8643" type="car" depart="0.03" departLane="free" departSpeed="max" fromTaz="63" toTaz="5">
<vehicle id="8928" type="car" depart="0.34" departLane="free" departSpeed="max" fromTaz="663" toTaz="1147">
</routes>
目前我在下面打印了所需的属性。
import xml.etree.cElementTree as ET
e = ET.parse('trip_049.rou.xml')
root = e.getroot()
for vehicle in root.findall('vehicle'):
id = vehicle.get('id')
origin = vehicle.get('fromTaz')
destination = vehicle.get('toTaz')
print id,origin,destination
哪个输出:
8643 63 5
8928 663 1147
但我需要将循环输出存储在numpy数组或等效数据中:
id origin destination
8643 63 5
8928 663 1147
谢谢你
答案 0 :(得分:2)
您可以简单地创建一个二维列表,然后在最后将其转换为numpy数组。示例 -
import xml.etree.cElementTree as ET
import numpy as np
e = ET.parse('trip_049.rou.xml')
root = e.getroot()
tdlist = []
for vehicle in root.findall('vehicle'):
id = vehicle.get('id')
origin = vehicle.get('fromTaz')
destination = vehicle.get('toTaz')
tdlist.append([id,origin,destination])
arraylst = np.array(tdlist)
tdlist
及arraylst
中的元素属于str
类型。如果你想要它们作为整数,那么你应该将它们转换为int as -
id = int(vehicle.get('id'))
origin = int(vehicle.get('fromTaz'))
destination = int(vehicle.get('toTaz'))