我有以下格式的YAML文件:
innings:
- 1st innings:
team: England
deliveries:
- 0.1:
batsman: ME Trescothick
bowler: Shoaib Akhtar
extras:
wides: 1
non_striker: AJ Strauss
runs:
batsman: 0
extras: 1
total: 1
- 0.2:
batsman: ME Trescothick
bowler: Shoaib Akhtar
non_striker: AJ Strauss
runs:
batsman: 0
extras: 0
total: 0
- 2nd innings:
team: Pakistan
deliveries:
- 0.1:
batsman: Shoaib Malik
bowler: D Gough
non_striker: Mohammad Hafeez
runs:
batsman: 2
extras: 0
total: 2
- 0.2:
batsman: Shoaib Malik
bowler: D Gough
extras:
wides: 5
non_striker: Mohammad Hafeez
runs:
batsman: 0
extras: 5
total: 5
我使用以下代码访问yaml数据:
^{pr2}$print语句给出了以下结果:
- 1st innings:
team: England
deliveries:
- 0.1:
batsman: ME Trescothick
bowler: Shoaib Akhtar
extras:
wides: 1
non_striker: AJ Strauss
runs:
batsman: 0
extras: 1
total: 1
- 0.2:
batsman: ME Trescothick
bowler: Shoaib Akhtar
non_striker: AJ Strauss
runs:
batsman: 0
extras: 0
total: 0
但当我试着用这句话进入第一局时:
print x.innings[0].1st innings
它抛出一个错误。我甚至尝试将字符串“1st innings”赋给一个变量并使用它。但它抛出了一个错误:
inn = "1st innings"
print x.innings[0].inn
我需要知道跑步的总次数。为此,我需要将列表[0.1, 0.2,...]
中每个球的总数相加。在
Converting to Python lists & dictionaries,你得到这个结构,称它为
x
。在注释中的一些值是
x.innings
或x['innings']
-返回由"1st innings"
和"2nd innings"
键控的Python字典列表x.innings[0]
-返回上面列表中的第一个字典x.innings[0]['1st innings']
-返回innings
列表中第一项中"1st innings"
键的字典值。x.innings[0]['1st innings']['deliveries']
-返回由0.1
和0.2
键控的Python字典列表。x.innings[0]['1st innings']['deliveries'][0]
-返回上面列表中的第一个字典x.innings[0]['1st innings']['deliveries'][0][0.1]
-返回deliveries
列表中第一项中0.1
键的JSON对象值。x.innings[0]['1st innings']['deliveries'][0][0.1]['runs']
-返回'runs'
的字典数据:
@laxmi23欢迎使用堆栈溢出。请阅读How to ask a good question一节,提出能得到更多答案和更多选票的问题。你也可能喜欢阅读How to create a mimimal, complete and verifiable example。在
你的问题很可能被投票否决了,因为在发帖之前你可能没有做充分的研究。尤其是YAML Tutorial on ^{} 的部分表示它返回一个Python对象。搜索Python Tutorial on Data Types可以看到如何索引各种Python对象,例如Lists和{a7},这正是您在这里需要的:
查看响应
^{pr2}${'innings': [{'1st innings': ...
的第一行,可以看到外部对象是一个字典,它包含一个字典列表。因此,访问Python对象就像Python数据类型教程使用方括号演示的那样。在正如我在上面的评论中所说的,Python字典键可以是任何散列的,甚至是一个float。所以为了找到
runs
,请使用0.1
作为数字而不是字符串。假设我们将load
响应捕获为x
。在相关问题 更多 >
编程相关推荐