【问题标题】:Remove a list from dictionary value lists using filter() in Python3在 Python3 中使用 filter() 从字典值列表中删除一个列表
【发布时间】:2021-12-21 00:04:19
【问题描述】:

我有一本字典,其中有 key: strvalue: 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


    【解决方案1】:

    你的字典理解差不多了:

    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']]}
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多