Python - 从列表中删除键/值元素并返回新列表

标签 python python-2.7 list

我一直在阅读其他一些 SO 文章,并了解我想要完成的事情的点点滴滴,但我尚未确定包含我的要求的答案。

我知道如何从 [1,2,3,4] 这样的简单列表中删除单个项目,但我有一个更复杂的列表,其中顺序/内容不可预测,我正在尝试删除一个元素来自:

list = [{u'role': u'OWNER', u'userByEmail': u'<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097d6c7a7d38496c64686065276a6664" rel="noreferrer noopener nofollow">[email protected]</a>'}, {u'specialGroup': u'projectWriters', u'role': u'READER'}, {u'specialGroup': u'projectOwners', u'role': u'READER'}, {u'specialGroup': u'projectReaders', u'role': u'READER'}, {u'role': u'READER', u'userByEmail': u'<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e0f1e7e0a6d4f1f9f5fdf8baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>'}, {u'view': {u'projectId': u'project-01', u'tableId': u'testing_tbl_2', u'datasetId': u'test2'}}, {u'view': {u'projectId': u'project-01', u'tableId': u'testing_tbl_3', u'datasetId': u'dtest2'}}, {u'view': {u'projectId': u'project-01', u'tableId': u'view1', u'datasetId': u'test2'}}]

我需要删除:

{u'role': u'READER', u'userByEmail': u'<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d7c6d0d792e3c6cec2cacf8dc0ccce" rel="noreferrer noopener nofollow">[email protected]</a>'}

并返回不存在该键/值元素的新列表。我可以做这样的事情(我更喜欢这种格式),但这仅返回过滤器正在查找的键/值元素。

>>> filter(lambda row: row.has_key('userByEmail') and row['userByEmail'] == '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccb8a9bfb8fd8ca9a1ada5a0e2afa3a1" rel="noreferrer noopener nofollow">[email protected]</a>', list)
[{u'role': u'OWNER', u'userByEmail': u'<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047061777035446169656d682a676b69" rel="noreferrer noopener nofollow">[email protected]</a>'}] 

如何从列表中删除元素,然后打印出缺少过滤元素的新列表?

最佳答案

将条件反转为

not (...)

所以

filter(lambda row: row.has_key('userByEmail') and row['userByEmail'] == '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196d7c6a6d28597c74787075377a7674" rel="noreferrer noopener nofollow">[email protected]</a>', list)

变成了

filter(lambda row: not (row.has_key('userByEmail') and row['userByEmail'] == '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb9f8e989fdaab8e868a8287c5888486" rel="noreferrer noopener nofollow">[email protected]</a>'), list)

关于Python - 从列表中删除键/值元素并返回新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526219/

相关文章:

python - 如何从列表中获取键和值以添加到字典中

python 27 - 多处理时 boolean 检查失败

python - 循环遍历Python字典总是产生不同的结果

python - 在 Python 2.7 中运行 MySQL 将 CSV 加载到 MySQL -

c# - 如何从 C# 中的列表或 var 中获取随机数量的详细信息

c++ - 需要列表设计(面向对象)建议

python - 如何在python中比较两个列表列表,然后将数据写入excel

用于在某些两个字符串之间提取字符串的 python 正则表达式

python - 关于在 gzip 文件上使用 seek

python - 换行符不适用于 python 2.7