将函数应用于dict中的值 [英] Applying a function to values in dict

查看:92
本文介绍了将函数应用于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中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆