在 Python3 中使用 filter() 从字典值列表中删除列表
Remove a list from dictionary value lists using filter() in Python3
我有一本字典,其中 key: str
和 value: list
。当键等于某个值并且该列表中的一个元素等于某个值时,我想从其值列表中删除某个列表。
例如,当 d["A"]=[[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]"
时,我想从 d["A"]
中删除其第二个索引值等于 3242413
的列表,以便键 A 处的新字典变为:d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]"
.
到目前为止,我尝试使用 filter() 和 dict comprehension 但无法想出一个干净的方法来做到这一点。当然总是有循环和删除的方法,但我想知道我们是否可以使用 filter() 来实现同样的事情?像 :
# d is the dictionary key: str value: list of lists
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
# 1. use filter
new_dict = dict(filter(lambda elem: elem[1].. != ,d.items())) # filter out those element inside list value does not equal to 3242413
# 2. use dict comprehension
new_dict = {key: value for (key, value) in d.items() if value ... == }
# so the new dict becomes
d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
你对字典的理解已经差不多了:
d = {}
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
d["B"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 1, "NEW"], [1982, "PEAR", 3242413, "OLD"]]
d = {k: [i for i in v if i[2] != 3242413] for (k, v) in d.items()}
给出:
{'A': [[0, 'APPLE', 1202021, 'NEW'], [1982, 'PEAR', 1299021, 'OLD']], 'B': [[0, 'APPLE', 1202021, 'NEW'], [8, 'PEAR', 1, 'NEW']]}
我有一本字典,其中 key: str
和 value: list
。当键等于某个值并且该列表中的一个元素等于某个值时,我想从其值列表中删除某个列表。
例如,当 d["A"]=[[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]"
时,我想从 d["A"]
中删除其第二个索引值等于 3242413
的列表,以便键 A 处的新字典变为:d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]"
.
到目前为止,我尝试使用 filter() 和 dict comprehension 但无法想出一个干净的方法来做到这一点。当然总是有循环和删除的方法,但我想知道我们是否可以使用 filter() 来实现同样的事情?像 :
# d is the dictionary key: str value: list of lists
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
# 1. use filter
new_dict = dict(filter(lambda elem: elem[1].. != ,d.items())) # filter out those element inside list value does not equal to 3242413
# 2. use dict comprehension
new_dict = {key: value for (key, value) in d.items() if value ... == }
# so the new dict becomes
d["A"]=[[0, "APPLE", 1202021, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
你对字典的理解已经差不多了:
d = {}
d["A"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 3242413, "NEW"], [1982, "PEAR", 1299021, "OLD"]]
d["B"] = [[0, "APPLE", 1202021, "NEW"], [8, "PEAR", 1, "NEW"], [1982, "PEAR", 3242413, "OLD"]]
d = {k: [i for i in v if i[2] != 3242413] for (k, v) in d.items()}
给出:
{'A': [[0, 'APPLE', 1202021, 'NEW'], [1982, 'PEAR', 1299021, 'OLD']], 'B': [[0, 'APPLE', 1202021, 'NEW'], [8, 'PEAR', 1, 'NEW']]}