本文介绍了将函数应用于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中的值
发布评论