繁体   English   中英

如何将相同的函数应用于字典数组中的每个值?

[英]How do I apply the same function to each value in an array of dicts?

我正在使用 Python 3.7。 我有一个字典数组,每个数组都有相同的键。 例如

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

如何将相同的函数应用于每个字典中某个键的值? 例如,我想将大写函数应用于使上述内容的值

arr_of_dicts = ({"st" : "IL"}, {"st" : "IL"}, {"st" : "IL"})

?

使用map() ,你可以让你的转换函数接受一个键来转换并返回一个 lambda,它充当映射方法。 通过使用先前传递的键 ( k ) 和传入的字典 ( d ),您可以返回一个新字典,其中字典的值转换为大写:

arr_of_dicts = ({"st" : "il"}, {"st" : "IL"}, {"st" : "Il"})

upper = lambda k: lambda d: {k: d[k].upper()} # your func
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

结果:

[{'st': 'IL'}, {'st': 'IL'}, {'st': 'IL'}]

如果您的字典有其他键,那么您可以先将原始字典扩展到新字典中,然后使用大写版本覆盖要转换的键属性,如下所示:

arr_of_dicts = [{"a": 5, "st" : "il"}, {"a": 7, "st" : "IL"}, {"a": 8, "st" : "Il"}]

upper = lambda k: lambda d: {**d, k: d[k].upper()}
res = map(upper('st'), arr_of_dicts) # mapping method

print(list(res))

结果:

[{'a': 5, 'st': 'IL'}, {'a': 7, 'st': 'IL'}, {'a': 8, 'st': 'IL'}]

您可能还喜欢熊猫。

如果你做了很多这样的事情,你应该检查pandas及其应用功能 它可以使这些事情变得尽可能快:

df = df.apply(your_func)

这是一个非常强大的工具,如果您愿意,您有时可以制作一些光滑且方便的单线笔。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM