在循环外部中断

2024-04-18 19:30:01 发布

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

我在python中有下面的代码,但是它说的是break outside of loop,而显然它在循环中的if语句中

import json
c=0
with open("test.json") as json_file:
        c+=1
        if(c>10):
                break
        json_data = json.load(json_file)
        print(json_data)

Tags: of代码testimportloopjsondataif
1条回答
网友
1楼 · 发布于 2024-04-18 19:30:01

没有循环。with不是循环,if也不是循环。你知道吗

看起来您缺少for语句。你知道吗

另外,还有一种更像Python的做事方式:

import json
import itertools

with open('test.json') as json_file:
    for _ in itertools.repeat(None, 10):
        json_data = json.load(json_file)
        print(json_data)

或者更简单:

import json

with open('test.json') as json_file:
    for _ in xrange(10):
        json_data = json.load(json_file)
        print(json_data)

相关问题 更多 >