将功能应用于字典的值

编程入门 行业动态 更新时间:2024-10-27 04:26:21
本文介绍了将功能应用于字典的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个列表 L 的字典,其中字典具有相同的键集。

I have a list L of dictionaries, where the dictionaries have the same set of keys.

我有另一个字典 d ,它也具有与之前的字典相同的一组键。

I have another dictionary d, which also has the same set of keys as the previous dictionaries.

对于密钥集中的每个键, d [key] 是可以应用于 L [i] [key] 的功能,即 d [key](L [i] [key ])。

For each key in the set of keys, d[key] is a function which can apply to L[i][key], i.e. d[key](L[i][key]).

我想使用<$ c $的值中的函数重置 L 中的字典值c> d ,即

I want to reset the values of dictionaries in L, using the functions in the values of d, i.e.

L[i][key] = d[key](L[i][key])

所有键和所有我。

如何以更多的pythonic方式做到这一点?谢谢。

How can I do it in a more pythonic way? Thanks.

例如。

d = {'a':int, 'b':myfun, 'c':yourfun} L[1] = {'a':`10`, 'b':5, 'c':1.4}

其中 int 是一个类型转换函数 int(), myfun 是一个可以取整数作为参数的函数, yourfun 是可以使用浮点数作为参数的另一个函数。 / p>

where int is a type conversion function int(), myfun is a function which can take an integer as its argument, and yourfun is another function which can take a floating number as its argument.

推荐答案

您可以使用列表和dict重新生成 L 理解:

You can regenerate L with the correct values using a list and dict comprehension:

L = [{k: d[k](v) for (k, v) in l.iteritems()} for l in L]

更多推荐

将功能应用于字典的值

本文发布于:2023-11-12 09:31:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   字典   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!