简体   繁体   English

如何利用列表推导的索引?

[英]How do I leverage an index with list comprehension?

I am trying to filter a JSON array based on a value contained in each of the arrays. 我试图根据每个数组中包含的值过滤JSON数组。 Provided some user input, I only want to return relevant values based on the type. 提供了一些用户输入,我只想根据类型返回相关值。

Sample json: 示例json:

{
    "routes": [
        {
            "name": "Golden Shower",
            "type": "Boulder",
            "rating": "V5",
            "stars": 5,
            "starVotes": 131,
            "pitches": ""
        },
        {
            "name": "Girls Only",
            "type": "Sport",
            "rating": "5.10a",
            "stars": 4.9,
            "starVotes": 156,
            "pitches": "1"
        }
    ],
    "success": 1
}

I have attempted to use a few variations of a code sample provided on a similar question, but am running in to issues due to slightly more complex data structure. 我试图使用在类似问题上提供的代码示例的一些变体,但由于稍微复杂的数据结构而导致问题。 See: how to filter json array in python 请参阅: 如何在python中过滤json数组

I have tried a few variations of code. 我尝试了一些代码变体。 All of the errors center around improper use of indices. 所有错误都以不正确的指数使用为中心。 Some things I've tried. 我试过的一些事情。

routeData = routesByGpsResp.json()
input_dict = routeData
output_dict = [x for x in input_dict if x['type'] == 'Sport']

error: sting indices must be integers 错误:sting索引必须是整数

output_dict = [x for x in input_dict.items() if ['routes'][x]['type'] == 'Sport']

error: list indices must be integers or slices, not tuple 错误:列表索引必须是整数或切片,而不是元组

I was able to print a list of route names using for statement an index, but cannot seem to figure it out for list comprehension. 我能够使用for语句打印一个路由名称列表,但似乎无法弄清楚列表理解。

for key in range(len(routeData['routes'])):
    print(routeData['routes'][key]['name'])

Is list comprehension the wrong way to go here? 列表理解是错误的方式去这里? Should I be using a for statement instead? 我应该使用for语句吗?

Any help is appreciated! 任何帮助表示赞赏!

Note: all your attempts are list comprehensions , while the variable name suggests a dict comprehension ( [Python]: PEP 274 -- Dict Comprehensions ). 注意:所有尝试都是列表推导 ,而变量名称表示字典 理解[Python]:PEP 274 - Dict Comprehensions )。

Here's an example how you could get output_dict (and below, output_list ) based on your input_dict , and the condition(s). 下面是一个示例,说明如何根据input_dict和条件获取output_dict (及以下, output_list )。 As a note: the dict comprehension nests a list comprehension (which alone constitutes the 2 nd example) for the "routes" key, while for all the other keys leaves the values unchanged: 作为注释: 字典理解嵌套了“路由”键的列表理解(仅构成第二个示例),而对于所有其他键,使值保持不变:

 >>> output_dict = {k: v if k != "routes" else [i for i in v if i["type"] == "Sport"] for k, v in input_dict.items()} >>> >>> from pprint import pprint >>> >>> pprint(output_dict) {'routes': [{'name': 'Girls Only', 'pitches': '1', 'rating': '5.10a', 'starVotes': 156, 'stars': 4.9, 'type': 'Sport'}], 'success': 1} >>> >>> # Or if you only want the list ... >>> output_list = [i for i in input_dict.get("routes", list()) if i["type"] == "Sport"] >>> >>> pprint(output_list) [{'name': 'Girls Only', 'pitches': '1', 'rating': '5.10a', 'starVotes': 156, 'stars': 4.9, 'type': 'Sport'}] 

In your first attempt: 在你的第一次尝试中:

output_dict = [x for x in input_dict if x['type'] == 'Sport']

x in input_dict iterates over the keys, so you are doing "routes"['type'] , but strings are indexes by integers, and not by a string, hence the error string indices must be integers x in input_dict遍历键,因此您正在执行"routes"['type'] ,但字符串是整数索引,而不是字符串,因此错误string indices must be integers

In your second attempt: 在你的第二次尝试中:

output_dict = [x for x in input_dict.items() if ['routes'][x]['type'] == 'Sport']

['routes'] is a list, and x is a tuple of ( key,value ) obtained by iterating over the dictionary input_dict , so ['routes'][x] raises a error: list indices must be integers or slices, not tuple ['routes']是一个列表, x是通过迭代字典input_dict获得的( key,value )元组,因此['routes'][x]引发error: list indices must be integers or slices, not tuple

The right way for a list-comprehension, as already pointed out by @cs95, is to iterate over the list of routes by for x in input_dict.get('routes') , get the dictionary for the value of key type that matches Sport 正如@ cs95已经指出的那样,列表理解的正确方法是for x in input_dict.get('routes')迭代for x in input_dict.get('routes')的路由列表,获取与Sport匹配的键type值的字典

print([x for x in input_dict.get('routes') if x.get('type') == 'Sport'])

The output is 输出是

[{'name': 'Girls Only', 'type': 'Sport', 'rating': '5.10a', 'stars': 4.9, 'starVotes': 156, 'pitches': '1'}]

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

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