繁体   English   中英

获取列表索引必须是整数或切片,而不是str

[英]Getting list indices must be integers or slices, not str

编写一个名为“ jsonFilter”的函数,该函数采用JSON格式的字符串作为对象数组格式的参数,其中每个对象都有键“质量”,“密度”,“温度”和“速度”,并且每个键都映射到浮点数。 此函数应以相同的格式将输入作为JSON字符串返回,但仅包含速度大于38.11的对象。

import json
def jsonFilter(JSON):
    load = json.loads(JSON)
    for key, value in load["velocity"]:
        if value > 38.11:
            return load['velocity'][key]

我得到列表索引必须是整数或片,而不是str。 我究竟做错了什么?

在没有看到实际输入的情况下,这有点困难,但是可能的问题是,正如您所说的,您正在获取JSON数组并尝试通过键访问它。 即,如果JSON参数是json对象的json数组,则它将作为字典列表加载。 列表只能通过整数访问。 在这种情况下,为了能够访问任何给定对象的“速度”,您首先需要使用整数索引到该对象。

IIUC,请执行以下操作:

import json
def jsonFilter(JSON):
    load = json.loads(JSON)
    return json.dumps([i for i in load if i['velocity']>38.11])

现在:

print(jsonFilter(your_json))

方法是:

"[{'density': 957.29, 'mass': 46.42, 'temperature': 73.39, 'velocity': 97.98}, {'density': 167.29, 'mass': 74.63, 'temperature': 26.29, 'velocity': 39.96}]"
import json 
def jsonFilter(JSON): 
    load = json.loads(JSON) 
    array = []
    for i in load:  
        if i['velocity'] > 38.11: 
            array.append(i)
    return json.dumps(array)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM