gpt4 book ai didi

Python:如何捕获异常并继续?

转载 作者:行者123 更新时间:2023-11-28 20:52:01 25 4
gpt4 key购买 nike

Why do you have a list of both numbers and some other kind of object? It seems like you're trying to compensate for a design flaw.

事实上,我希望它以这种方式工作,因为我想保留已经在 J​​sonedData() 中编码的数据,然后我希望 json 模块给我一些方法来插入“原始”项目数据而不是默认值,以便编码的 JsonedData 可以重用。

这是代码,谢谢

import json
import io
class JsonedData():
def __init__(self, data):
self.data = data
def main():
try:
for chunk in json.JSONEncoder().iterencode([1,2,3,JsonedData(u'4'),5]):
print chunk
except TypeError: pass# except come method to make the print continue
# so that printed data is something like:
# [1
# ,2
# ,3
# ,
# ,5]

最佳答案

try/except 放在 json.JSONEncoder().encode(item) 的循环中:

print "[",
lst = [1, 2, 3, JsonedData(u'4'), 5]
for i, item in enumerate(lst):
    try:
        chunk = json.JSONEncoder().encode(item)
    except TypeError:
pass
else:
print chunk
finally:
# dont print the ',' if this is the last item in the lst
if i + 1 != len(lst):
print ","
print "]"

关于Python:如何捕获异常并继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com