首页 > 解决方案 > 打印我的提要的前 10 行

问题描述

import json 

with open('output.json', encoding='utf-8') as json_file:  
   output = json.loads(json_file.read())
feeds = []
for feed in output ['posts']:
   feeds.append (feed)
print (feeds[1]['title'])

我试图只打印数据的前 10 行。我尝试了“枚举”和其他代码,但它们似乎都不起作用。关于如何仅获得输出的前 10 个标题的任何想法?

标签: pythonjsonfeed

解决方案


用作[:10]切片将使您最多获得前 10 个元素:

import json

with open('output.json', encoding='utf-8') as json_file:  
    output = json.loads(json_file.read())
feeds = []
for feed in output ['posts'][:10]: #   <---- Change on this line
    feeds.append (feed)
print (feeds[1]['title'])

推荐阅读