python - 如何从列表中删除?

标签 python

假设我有以下列表:

array1 = ['A', 'C', 'Desk']

另一个数组包含:

array2 = [{'id': 'A', 'name': 'Greg'}, 
{'id': 'Desk', 'name': 'Will'},
{'id': 'E', 'name': 'Craig'},
{'id': 'G', 'name': 'Johnson'}]

从列表中删除项目的好方法是什么?以下似乎不起作用

for item in array2:
   if item['id'] in array1:
     array2.remove(item)

最佳答案

您还可以为此使用列表推导式:

>>> array2 = [{'id': 'A', 'name': 'Greg'},
... {'id': 'Desk', 'name': 'Will'},
... {'id': 'E', 'name': 'Craig'},
... {'id': 'G', 'name': 'Johnson'}]
>>> array1 = ['A', 'C', 'Desk']
>>> filtered = [item for item in array2 if item['id'] not in array1]
>>> filtered
[{'id': 'E', 'name': 'Craig'}, {'id': 'G', 'name': 'Johnson'}]

关于python - 如何从列表中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304895/

相关文章:

python - 无法在 pygame 中改变颜色?

python - 如何从数据框中找到句子中单词和字符的最大数量?

python - 用 pandas 绘制直方图和正态密度

python - 如何从字典列表中找到键的值?

python - 类型错误 : 'dict' object is not callable

python - 使用 urllib 删除 python 中的换行符

通过 multiprocessing.pool 的 Python3 并行代码比顺序代码慢

python - 如何使用 Django Rest Framework 在单个请求中反序列化多个文件和表单数据?

python - 创建重复行并更改特定列中的值

python - Pandas 面板最大