我有这本字典,我想列一张有身份证的清单。。如果他们的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
你可以在这里使用列表理解。在
代码中发现的基本问题
实际上,您需要使用}语句的结尾,如下所示
:
来标记if
和{不要使用任何内置名称作为变量名。在这种情况下,
list
。要从字典中获取值,只需要使用
["key"]
方法来获取它。点符号不起作用。所以你的固定代码应该是这样的
除此之外,检查变量是否真实的python方法是
^{pr2}$所以我们不检查
或者
引用PEP-8,Python代码的风格指南
解决这个问题的最好方法是将list comprehension与过滤条件一起使用,如下所示
它将根据旧的iterable创建一个新列表,在本例中是
categories
。在“后循环”:
相关问题 更多 >
编程相关推荐