簡體   English   中英

打破循環Python

[英]Break outside of Loop python

我在python中有以下代碼,但這是說在循環外中斷,顯然是在循環的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)

沒有循環。 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM