Apply function to all items in a list Python

一个人想着一个人 提交于 2020-01-30 09:22:04

问题


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

for example:

myCoolFunction(75)

would produce a new value

So far I am using this:

x = 0
newValues = []

for value in my_list:

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

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

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


回答1:


You can use map approach:

list(map(myCoolFunction, my_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.




回答2:


This question is heavily tagged with Pandas related things. And so here is how the pythonic mapping and list comprehension techniques mentioned above are done with Pandas.

import pandas as pd

def myCoolFunction(i):
    return i+1

my_list = [1,2,3]
df = pd.DataFrame(index=my_list, data=my_list, columns=['newValue']).apply(myCoolFunction)



来源:https://stackoverflow.com/questions/55549585/apply-function-to-all-items-in-a-list-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!