python 使用 lambda 和 map 从字典列表中删除键/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1875932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting key/value from list of dictionaries using lambda and map
提问by webley
I have a list of dictionaries that have the same keys within eg:
我有一个字典列表,其中包含相同的键,例如:
[{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....]
I'm trying to delete k1 from all dictionaries within the list.
我正在尝试从列表中的所有词典中删除 k1。
I tried
我试过
map(lambda x: del x['k1'], list)
but that gave me a syntax error. Where have I gone wrong?
但这给了我一个语法错误。我哪里错了?
回答by Ned Batchelder
lambda bodies are only expressions, not statements like del
.
lambda 主体只是表达式,而不是像del
.
If you haveto use map and lambda, then:
如果必须使用 map 和 lambda,则:
map(lambda d: d.pop('k1'), list_of_d)
A for loop is probably clearer:
for 循环可能更清楚:
for d in list_of_d:
del d['k1']