[英]Nested list comprehension dict and list python
我有一个字典列表,其中有很多键,并且只想将每个字典的键价格值过滤到一个列表中。 我正在使用下面的代码,但无法正常工作...
print [b for a:b in dict.items() if a='price' for dict in data]
在此先感谢您的帮助!
我认为您需要以下内容(如果data
是您的“词典列表”):
[d.get('price') for d in data]
我正在做的是,遍历字典列表,并对每个字典使用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]
>>>
您可以通过以下方式添加显式的if-check来删除输出列表中的None
: [d['price'] for d in data if 'price' in d]
。
您的代码的评论:
[b for a:b in dict.items() if a='price' for dict in data]
a:b
应该是a, b
a='price'
应该是a == 'price'
(misspell ==运算符为=) 这不是错误,使用内置类型名称作为变量名称是不好的做法。 您不应将“ dict”,“ list”,“ str”等用作变量(或函数)名称。
您的代码的正确形式是:
[b for dict in data for a, b in dict.items() if a == 'price' ]
for a, b in dict.items() if a == 'price'
不需要for a, b in dict.items() if a == 'price'
循环,则for a, b in dict.items() if a == 'price'
, setdefualt(key)
简单的get(key)
, setdefualt(key)
或[key]
可以更快地进行无循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.