You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取JSON文件中points的数量并在Python循环中正确使用?

问题分析与解决

你的代码报错是因为len()返回的是整数,而for i in [整数]这种写法不成立——Python的for...in需要遍历可迭代对象(比如列表、range对象),直接遍历整数会抛出TypeError: 'int' object is not iterable。

解决方法有两种:

方法1:用range()包裹len()生成索引序列

修改循环部分为:

for i in range(len(data[0]["results"]["points"])):
    print(data[0]["results"]["points"][i]["name"], ': ')

range(len(...))会生成从0到列表长度-1的整数序列,这样就能通过索引遍历列表元素。

方法2:直接遍历列表元素(更推荐的Pythonic写法)

不需要索引,直接遍历points列表里的每个字典对象:

for point in data[0]["results"]["points"]:
    print(point["name"], ': ')

这种写法更简洁,也避免了索引操作可能带来的错误。

额外优化:

原代码中的json_file.close()是多余的——with语句会在代码块结束后自动关闭文件,所以可以删掉这行,简化代码为:

import json

with open('test.json') as json_file:
    data = json.load(json_file)

for point in data[0]["results"]["points"]:
    print(point["name"], ': ')

内容的提问来源于stack exchange,提问作者Adrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:35:17