问题描述
我正在寻找一种使用 lambda 或列表理解来更改列表中字典中的值的方法
list_of_objects = [
{'note': 'note1','comments': 'Test comments',elem': 1},{'note': 'note2','comments': None,elem': 2}
]
我需要遍历这个列表,用 None 找到每个字典中的每个值,并用文本“没有提供评论”替换这个值
预期结果:
[{'note': 'note1','comments': 'Test comments'
'elem': 1},'comments': 'No comments was provided'
'elem': 2}]
我可以使用标准的循环操作来做到这一点。但是我们正在寻找机会使用 lambda 或列表理解来最小化我的代码
解决方法
见下文(我认为 for 循环带来更好的可读性)
list_of_objects = [
{'note': 'note1','comments': 'Test comments','elem': 1},{'note': 'note2','comments': None,'elem': 2}
]
lst = [{k: v if k != 'comments' else v if v else 'no comments' for k,v in entry.items()} for entry in
list_of_objects]
print(lst)
输出
[{'note': 'note1','comments': 'no comments','elem': 2}]