python for循环输出为数组
我有XMl模拟输出,有许多python for循环输出为数组,python,xml,python-2.7,for-loop,numpy,Python,Xml,Python 2.7,For Loop,Numpy,我有XMl模拟输出,有许多车辆行,如: <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" fr
车辆
行,如:
<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>
哪些产出:
8643 63 5
8928 663 1147
但我需要将循环输出存储在numpy数组或类似的数组中:
id origin destination
8643 63 5
8928 663 1147
感谢您的支持您只需创建一个二维列表,然后在最后将其转换为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-
id = int(vehicle.get('id'))
origin = int(vehicle.get('fromTaz'))
destination = int(vehicle.get('toTaz'))
您希望它们作为二维numpy阵列吗?您希望元素的类型为字符串?是2-d;对于示例中的元素,类型为整数,但稍后可能会添加一些字符串元素。我将从示例中删除str
id = int(vehicle.get('id'))
origin = int(vehicle.get('fromTaz'))
destination = int(vehicle.get('toTaz'))