【发布时间】:2021-01-30 03:05:18
【问题描述】:
我在删除嵌套在字典列表中的列表的第二项时遇到问题。我认为可能是因为有几个空列表,所以索引不起作用。 如何删除每个嵌套列表对的第二项,同时跳过空列表?
最后,嵌套列表应该被展平,因为它不再有第二对了。
列表如下所示:
list_dict = [{"name": "Ken", "bla": [["abc", "ABC"],["def", "DEF"]]},
{"name": "Bob", "bla": []}, #skip the empty list
{"name": "Cher", "bla":[["abc", "ABC"]]}]
期望的输出:
wanted = [{"name": "Ken", "bla": ["abc", "def"]},
{"name": "Bob", "bla": []},
{"name": "Cher", "bla":["abc"]}]
我的代码:
for d in list_dict:
for l in list(d["bla"]):
if l is None:
continue #use continue to ignore the empty lists
d["bla"].remove(l[1]) #remove second item of every nested list pair (gives error).
【问题讨论】:
-
最后一行缩进太多。
-
顺便说一句,我猜
if l is None:永远不会是真的,因为它总是list而不是None。
标签: python list loops dictionary nested