Python 如何执行单行dict删除操作

Python 如何执行单行dict删除操作,python,list,list-comprehension,Python,List,List Comprehension,有没有一种方法可以在一行中完成以下操作 [del item for item in new_json if item['Country'] in countries_to_remove] 上面给出了一个语法错误,您不能使用它。这就是为什么会出现SyntaxError 您可以使用列表理解创建一个新的列表,而不需要您不想要的元素,如下所示 [item for item in new_json if item['Country'] not in countries_to_remove] list(

有没有一种方法可以在一行中完成以下操作

[del item for item in new_json if item['Country'] in countries_to_remove]
上面给出了一个
语法错误

,您不能使用它。这就是为什么会出现
SyntaxError

您可以使用列表理解创建一个新的列表,而不需要您不想要的元素,如下所示

[item for item in new_json if item['Country'] not in countries_to_remove]
list(filter(lambda x: x['Country'] not in countries_to_remove, new_json))
new_json[:] = [x for x in new_json if x['Country'] not in countries_to_remove]
这实际上相当于,

result = []
for item in new_json:
    if item['Country'] not in countries_to_remove:
        result.append(item)

这种操作称为筛选列表,您可以使用内置的
filter
函数,如下所示

[item for item in new_json if item['Country'] not in countries_to_remove]
list(filter(lambda x: x['Country'] not in countries_to_remove, new_json))
new_json[:] = [x for x in new_json if x['Country'] not in countries_to_remove]

正如所建议的,如果您只想改变原始列表,那么可以使用切片分配,如下所示

[item for item in new_json if item['Country'] not in countries_to_remove]
list(filter(lambda x: x['Country'] not in countries_to_remove, new_json))
new_json[:] = [x for x in new_json if x['Country'] not in countries_to_remove]
是python中的语句,列表理解中不能有语句(只能有表达式)。为什么不创建一个新的列表或字典,其中不包括您想要删除的项目呢。范例=

new_json = [item for item in new_json if item['Country'] not in countries_to_remove]

好主意,这就是我最后要做的。而且,如果您需要执行适当的操作,您可以使用切片分配:
new_json[:]=[item for item in…]
请添加示例数据。你有什么输入,你想要什么输出。