简体   繁体   English

使用Lambda从字典列表中删除dict元素

[英]Remove dict element from list of dicts using lambda

New to python here: python的新功能:

I'm trying to create a new list where every dict from initial list has an element removed, it exists: 我正在尝试创建一个新列表,其中初始列表中的每个字典都删除了一个元素,该元素存在:

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: del d["y"] if "y" in d, arraylist)

I know I can do it using for , using del. 我知道我可以使用for 使用 del。 But I'm looking to learn something new. 但是我正在寻找新的东西。

Use a list comprehension: 使用列表理解:

In [26]: [{x:d[x] for x in d if x != 'y'} for d in arraylist]
Out[26]: [{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]

You can use filter like this 您可以使用这样的过滤器

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: dict(filter(lambda (k,v): k != "y", d.iteritems())), arraylist)

You can't use del in a lambda function because del is a statement and a lambda 's body can only be a single expression. 您不能在lambda函数中使用del ,因为del是一条语句,而lambda的主体只能是单个表达式。 You can't put a statement inside an expression. 您不能在表达式中放入语句。 You could make it work with an ordinary function: 您可以使其与普通函数一起工作:

def delete_y(d):
    if "y" in d:
        del d['y']
    return d

Note that using del like this modifies the dictionary d in place. 请注意,像这样使用del会适当地修改字典d This means that returning the modified dictionary (and using the return value to build a new list) is sort of redundant. 这意味着返回修改后的字典(并使用返回值构建新列表)是多余的。 The original data structure the dictionary came from will already have the modified version. 词典所来自的原始数据结构将已经具有修改后的版本。

Maybe its not the shortest way, but it is definitely a convenient way to remove items from a list: 也许它不是最短的方法,但绝对是从列表中删除项目的便捷方法:

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]

print arraylist

def containsY(d):
    if 'y' in d.keys():
        del d['y']
        return True
    return False

filter(containsY, arraylist)

print arraylist

output: 输出:

[{'y': 2, 'x': 1}, {'y': 2, 'x': 3}, {'y': 2, 'x': 5}, {'y': 2, 'x': 33}, {'y': 8, 'x': 1}]
[{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM