【问题标题】:Dict list comprehension in PythonPython中的字典列表理解
【发布时间】: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


    【解决方案1】:

    使用推导式时,您实际上是在创建一个新推导式,因此“变异”超出了上下文。但假设你想要相同的输出:

    mutable_func = lambda data: data*10
    
    print([{**d, "age": mutable_func(d["age"])} for d in sample_dict_list])
    

    在我的示例中,您将使用 **d 解压缩字典并添加另一个键值来覆盖 d 中的现有键值。

    【讨论】:

      【解决方案2】:

      这里有点复杂:

      def list_mutate_dict(list1, mutable_func):
          [{key: (mutable_func(value) if key == 'age' else value) for key, value in item.items()} for item in list1]
      

      解释(由内而外):

      首先,如果需要,您可以在赋值中的条件中改变值,保持所有其他值相同。
      然后,您通过迭代所有项对所有字典项执行此操作。
      最后,您对列表中的所有字典执行此操作。

      我要补充一点,这些类型的列表推导式不被认为是最佳实践,并且通常会导致非常混乱和难以维护的代码。

      【讨论】:

      • 谢谢。这也有效,但上面的答案似乎很简单。这是另一种很好的替代方式。
      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2022-11-22
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多