在 python 字典中映射值 - Mapping over values in a python dictionary

10/14 14:04
阅读数 0

问题:

Given a dictionary { k1: v1, k2: v2 ... } I want to get { k1: f(v1), k2: f(v2) ... } provided I pass a function f .给定字典{ k1: v1, k2: v2 ... }我想得到{ k1: f(v1), k2: f(v2) ... }前提是我传递了一个函数f

Is there any such built in function?有没有这样的内置功能? Or do I have to do或者我必须做

dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()])

Ideally I would just write理想情况下我会写

my_dictionary.map_values(f)

or或者

my_dictionary.mutate_values_with(f)

That is, it doesn't matter to me if the original dictionary is mutated or a copy is created.也就是说,原始字典是否发生变异或创建副本对我来说无关紧要。


解决方案:

参考一: https://en.stackoom.com/question/pJKy
参考二: https://stackoom.com/question/pJKy
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部