python for循环输出为数组

时间:2015-09-09 15:36:56

标签: python xml python-2.7 for-loop numpy

我有 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

谢谢你

1 个答案:

答案 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)

tdlistarraylst中的元素属于str类型。如果你想要它们作为整数,那么你应该将它们转换为int as -

id = int(vehicle.get('id'))
origin = int(vehicle.get('fromTaz'))
destination = int(vehicle.get('toTaz'))