将函数应用于列表Python中的所有项目 [英] Apply function to all items in a list Python

查看:72
本文介绍了将函数应用于列表Python中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将功能应用于列表.该函数需要一个值并产生另一个值.

I am trying to apply a function to a list. The function takes a value and produces another.

例如:

myCoolFunction(75)

将产生新的价值

到目前为止,我正在使用它:

So far I am using this:

x = 0
newValues = []

for value in my_list:

    x = x + 1
    newValues.append(myCoolFunction(value))
    print(x)

我正在处理大约125,000个值,并且运行速度似乎不太有效.

I am working with around 125,000 values and the speed at which this is operating does not seem very efficient.

是否存在将函数应用于值的更多pythonic方法?

Is there a more pythonic way to apply the function to the values?

推荐答案

您可以使用 map 方法:

You can use map approach:

list(map(myCoolFunction, my_list))

这会将定义的函数应用于 my_list 的每个值,并创建一个映射对象(3.x).在其上调用 list()会创建一个新列表.

This applies defined function on each value of my_list and creates a map object (3.x). Calling a list() on it creates a new list.

这篇关于将函数应用于列表Python中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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