python 在使用生成器表达式找不到值时出现StopIteration错误

qcbq4gxm  于 2022-12-28  发布在  Python
关注(0)|答案(2)|浏览(119)

我有一个json文件,加载到一个变量中,如果这个文件不存在,我会做一个字典,很快就会变成json文件,很好,我试着寻找字典中的特定元素,这就是为什么我使用生成器表达式。
我是这样使用它的:

Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}

name = "asdadsefttytryrty"

get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)

字典data应该是这样的

{
    "News": {},
    "Records": {},
    "Profiles": [
        {
            "Name": "123rd453",
            "ID": "1",
            "Password": "dfsdfee",
            "Image": "image"
        },
        {
            "Name": "asdadsefttytryrty",
            "ID": "2",
            "Password": "12345",
            "Image": "image"
        }
    ]
}

好吧,如果我找的元素不存在,这就有问题了:停止迭代
所以为了检查元素是否存在,我想用if-else来执行某些操作,但是我做不到,所以我决定用try-except作为临时解决方案,我认为它不可靠。

Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}

name = "asdadsefttytryrty"
try:
    get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
    print("exist")
except:
    print("Doesn't exist")

这样做是正确的吗?

gg58donl

gg58donl1#

不要把事情搞复杂,你可以简单地这样做:

from os import path

data = {}
name = "asdadsefttytryrty"

if (path.exists("./data.json")):
    with open('data.json') as f:
        data = json.load(f)
else:
    data = {
        "News": {},
        "Records": {},
        "Profiles": []
    }

if name in data["Profiles"]:
    print("Exists")
else:
    print("Doesn't exist")

使用os模块中的path.exists()方法检查某个路径是否存在。
在一开始就声明变量是一个很好的做法。

4ioopgfo

4ioopgfo2#

next在给定的迭代器耗尽时确实会引发StopIteration,所以您所做的基本上是正确和可靠的,唯一要添加的是您所期望的特定异常,以便不捕获诸如KeyboardInterrupt之类的意外异常:

try:
    get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
    print("exist")
except StopIteration:
    print("Doesn't exist")

也就是说,在这种情况下,使用for-else结构编写的代码可能会更干净、更可读:

for get in Data["Profiles"]:
    if name in (get["Name"], get["ID"]):
        print("Exists")
else:
    print("Doesn't exist")

相关问题