python for循环输出为数组

2024-10-03 13:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

先谢谢你


Tags: idfreegettypeorigincardestinationmax
1条回答
网友
1楼 · 发布于 2024-10-03 13:23:23

您只需创建一个二维列表,然后在最后将其转换为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类型。如果你想让它们成为整数,那么你应该把它们转换成整数-

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

相关问题 更多 >