将函数应用于dict中的值

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

我想将一个函数应用于dict中的所有值,并将其存储在单独的dict中。我只是试图看看我可以玩python,想看看我可以如何重写这样的一个例子。

I want to apply a function to all values in dict and store that in a separate dict. I am just trying to see how I can play with python and want to see how I can rewrite something like this

for i in d: d2[i] = f(d[i])

d2[i] = f(d[i]) for i in d

编写它的第一种方式当然可以,但我正在设法研究如何更改python语法

The first way of writing it is of course fine, but I am trying to figure how python syntax can be changed

推荐答案

如果您使用的是Python 2.7或3.x:

If you're using Python 2.7 or 3.x:

d2 = {k: f(v) for k, v in d1.items()}

其中相当于:

d2 = {} for k, v in d1.items(): d2[k] = f(v)

否则:

d2 = dict((k, f(v)) for k, v in d1.items())

更多推荐

将函数应用于dict中的值

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

发布评论

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

>www.elefans.com

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