【发布时间】:2021-12-21 00:04:19
【问题描述】:
我有一本字典,其中有 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"]]
【问题讨论】:
标签: python python-3.x dictionary lambda