根据满足条件的字典中的值创建列表

2024-10-03 00:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这本字典,我想列一张有身份证的清单。。如果他们的hasCategory是真的。在

categories = [{'Id': 1350, 'hasCategory': True},
              {'Id': 113563, 'hasCategory': True},
              {'Id': 328422, 'hasCategory': False}]

在这个例子中,我的结果列表应该是

^{pr2}$

我试着用上面的代码

list =[]    
for item in categories:
    if item.hasCategory is True:
        list.push(item.Id) 

但当我试图运行我的应用程序时,我遇到了一个错误

for item in categories
                       ^
SyntaxError: invalid syntax

Tags: 代码inidfalsetrue列表for字典
3条回答

你可以在这里使用列表理解。在

>>> categories=   [{ 'Id': 1350, 'hasCategory': True},
               { 'Id': 113563, 'hasCategory': True},
               { 'Id': 328422, 'hasCategory': False}]
>>> [i['Id'] for i in categories if i['hasCategory'] == True]
[1350, 113563]

代码中发现的基本问题

  1. 实际上,您需要使用:来标记if和{}语句的结尾,如下所示

  2. 不要使用任何内置名称作为变量名。在这种情况下,list

  3. 要从字典中获取值,只需要使用["key"]方法来获取它。点符号不起作用。


所以你的固定代码应该是这样的

result = []                      # list is a built-in name. Don't use that
for item in categories:          # : at the end
    if item["hasCategory"]:      # : at the end
        result.push(item["Id"])

除此之外,检查变量是否真实的python方法是

^{pr2}$

所以我们不检查

if item["hasCategory"] == True:

或者

if item["hasCategory"] is True:    # Never use `is` to compare values

引用PEP-8,Python代码的风格指南

Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

解决这个问题的最好方法是将list comprehension与过滤条件一起使用,如下所示

>>> [item["Id"] for item in categories if item["hasCategory"]]
[1350, 113563]

它将根据旧的iterable创建一个新列表,在本例中是categories。在

“后循环”:

for item in categories:

相关问题 更多 >