【发布时间】:2020-10-18 19:05:09
【问题描述】:
我是 python 新手。我正在努力学习理解,但我目前被这个场景困住了。我可以做这个突变
sample_dict_list = [{'name': 'Vijay', 'age':30, 'empId': 1}, {'name': 'VV', 'age': 10, 'empId': 2},
{'name': 'VV1', 'age': 40, 'empId': 3}, {'name': 'VV2', 'age': 20, 'empId': 4}]
def list_mutate_dict(list1, mutable_func):
for items in list1:
for key,value in items.items():
if(key == 'age'):
items[key] = mutable_func(value)
return
mutable_list_func = lambda data: data*10
list_mutate_dict(sample_dict_list, mutable_list_func)
print(sample_dict_list)
[{'name': 'Vijay', 'age': 300, 'empId': 1}, {'name': 'VV', 'age': 100, 'empId': 2}, {'name': 'VV1', 'age': 400, 'empId': 3}, {'name': 'VV2', 'age': 200, 'empId': 4}]
仅带有“年龄”键的字典被变异并返回
这很好用。但是我正在尝试使用单行理解。我不确定它是否可以完成。
print([item for key,value in item.items() if (key == 'age') mutable_list_func(value) for item in sample_dict_list])
THis is the op - [{'age': 200}, {'age': 200}, {'age': 200}, {'age': 200}] which is incorrect. It just takes in the last value and mutates and returns as a dict list
这可以在“嵌套”列表字典理解中完成吗?
【问题讨论】:
标签: python-3.x list-comprehension dictionary-comprehension