使用python解析使用逗号分隔的多个键的yaml

时间:2016-12-13 22:12:20

标签: python yaml

我正在尝试阅读商业软件生成的YAML文件。 test.yml的摘录如下:

%YAML 1.1 
---
VesselTypes:
  - Name: Tanker
    Length: 103
    Draughts:
      - Name: Draught1
        Mass: 9017.95
        MomentOfInertiaTensorX, MomentOfInertiaTensorY, MomentOfInertiaTensorZ:
          - [254.9374465E3, 1, 2]
          - [3, 5.979802645E6, 4]
          - [7, 8, 5.979802645E6]
          - [9, 10, 11]

然后,在使用python解析此文件时:

#filename: test.py
import yaml

with open('test.yml', 'r') as f:
        data = yaml.load(f)

print(data['VesselTypes'][0]['Draughts'][0]['Name'])

#This would work
print(data['VesselTypes'][0]['Draughts'][0]['MomentOfInertiaTensorX, MomentOfInertiaTensorY, MomentOfInertiaTensorZ'])

print('----------------------------------------------------')
#This would give error
print(data['VesselTypes'][0]['Draughts'][0]['MomentOfInertiaTensorX'])

有关如何解析数据的任何建议?我刚刚开始学习YAML格式和python两者,所以有点困惑。

1 个答案:

答案 0 :(得分:1)

使用列表解包来提取没有循环的列表。

x_moment, y_moment, z_moment = data['VesselTypes'][0]['Draughts'][0]['MomentOfInertiaTensorX, MomentOfInertiaTensorY, MomentOfInertiaTensorZ']