嵌套列表理解字典和列表python

use*_*162 2 python dictionary list

我有一个词典列表,其中一个词典包含许多键,并且只想将每个词典的键价值过滤到列表中.我使用下面的代码但没有工作......

print [b for a:b in dict.items() if a='price' for dict in data]
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助!

Gri*_*han 5

我认为你需要像下面这样的东西(如果data是你的"dicts列表"):

[d.get('price') for d in data]
Run Code Online (Sandbox Code Playgroud)

我正在做的是,迭代dicts列表和每个dict使用get('price')(因为get()不抛出键异常)来读取'price'键的值.
注意:避免使用'dict'作为变量名,因为它是构建内类型名称.

例:

>>> data = [ {'price': 2, 'b': 20}, 
             {'price': 4, 'a': 20}, 
             {'c': 20}, {'price': 6, 'r': 20} ]  # indented by hand
>>> [d.get('price') for d in data]
[2, 4, None, 6]
>>> 
Run Code Online (Sandbox Code Playgroud)

您可以None在输出列表中删除,通过添加显式if-check为:[d['price'] for d in data if 'price' in d].

评论你的代码:

[b for a:b in dict.items() if a='price' for dict in data]
Run Code Online (Sandbox Code Playgroud)
  1. a:b应该有愚蠢的语法错误a, b
  2. 二,if条件中的语法错误 - a='price'应该是a == 'price' (misspell == operator as =)
  3. 嵌套循环的顺序是错误的(在列表压缩中我们稍后编写嵌套循环)
  4. 这不是错误,使用内置类型名称作为变量名称是不好的做法.你不应该使用'dict','list','str'等作为变量(或函数)名称.

    正确的代码形式是:

     [b for dict in data for a, b in dict.items() if a == 'price' ]
    
    Run Code Online (Sandbox Code Playgroud)
  5. 在您的列表中,压缩表达式for a, b in dict.items() if a == 'price'循环是不必要的 - 简单的get(key),setdefualt(key)或者在[key]没有循环的情