简体   繁体   English

Python嵌套列表理解错误

[英]Python Nested List Comprehension Error

I'm trying to convert a normal nested iteration into a nest list comp and I'm having trouble. 我正在尝试将普通的嵌套迭代转换为嵌套列表comp,但遇到了麻烦。

for k in r.json()['app_list']:
    for i in titles:
        if k['name'] == i['name'] and k['platform'] == i['platform']:
            array.append(session.get(k['api_url'], headers=headers).json())
return array

Works fine, however 工作正常,但是

return [session.get(k['api_url'], headers=headers).json()
        for i in titles for k in r.json()
        if k['name'] == i['name'] and k['platform'] == i['platform']]

throws this error 引发此错误

if k['name'] == i['name'] and k['platform'] == i['platform']]
TypeError: string indices must be integers

You have your nesting order wrong and you forgot to get the 'app_list' key from the r.json() dictionary. 您的嵌套顺序错误,并且忘记了从r.json()字典中获取'app_list'键。

List comprehension loops are still listed in the same order, left to right as you nest them. 列表理解循环仍以相同的顺序列出,嵌套时从左到右。 In other words, use the same order as your original nested for statements: 换句话说,使用原始嵌套for语句相同的顺序

return [session.get(k['api_url'], headers=headers).json()
        for k in r.json()['app_list']
        for i in titles
        if k['name'] == i['name'] and k['platform'] == i['platform']]

The above was reached simply by putting everything in the array.append() call at the front , then removing the : colons from the for and if statements and putting the result inside [...] square brackets. 以上是通过把一切都在简单地达到array.append()调用在前面 ,然后去除:冒号来自forif语句,并把结果里面[...]方括号。

You forgot the ['app_list'] subscription to the r.json() , and that's the actual cause of the exception; 您忘记了对r.json()['app_list']订阅,这是导致异常的真正原因; r.json() produces a dictionary, so each k was bound to a key from that dictionary, making the k['name'] subscription fail. r.json()生成一个字典,因此每个k都绑定到该字典中的一个 ,从而导致k['name']订阅失败。

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

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