gpt4 book ai didi

python - 列表索引超出范围(使用 json)

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:13 25 4
gpt4 key购买 nike

我导入了 json 并按名称过滤它。

def lootprice(json_object, name):
needobj = [obj for obj in json_object if obj['name'] == name][0]
if needobj['have'] < needobj['max']:
return needobj['price']

它工作了一段时间,然后显示这种错误:

needobj = [obj for obj in json_object if obj['name'] == name][0] 

IndexError: list index out of range

最佳答案

[obj for obj in json_object if obj['name'] == name] 返回空,这意味着 json_object 中没有搜索到的名称。您应该捕获该异常并相应地返回一些内容。

def lootprice(json_object, name):
try:
needobj = [obj for obj in json_object if obj['name'] == name][0]
except IndexError:
# Return something that tells the user no results where found
return None
if needobj['have'] < needobj['max']:
return needobj['price']

完整示例在这里:

def lootprice(json_object, name):
try:
needobj = [obj for obj in json_object if obj['name'] == name][0]
except IndexError:
return None
if needobj['have'] < needobj['max']:
return needobj['price']

my_object = [
{'obj_id': 1, 'name': 'test1', 'have': 12, 'max': 50, 'price': 11},
{'obj_id': 2, 'name': 'test2', 'have': 12, 'max': 50, 'price': 22},
{'obj_id': 4, 'name': 'test4', 'have': 12, 'max': 50, 'price': 44},
{'obj_id': 5, 'name': 'test5', 'have': 12, 'max': 50, 'price': 55}
]

lootprice(my_object, 'test1') # Returns 11
lootprice(my_object, 'test2') # Returns 22
lootprice(my_object, 'test3') # Returns None
lootprice(my_object, 'test4') # Returns 44
lootprice(my_object, 'test5') # Returns 55

关于python - 列表索引超出范围(使用 json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552624/

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