简体   繁体   中英

Apply function to each element of a list

Suppose I have a list like:

mylis = ['this is test', 'another test']

How do I apply a function to each element in the list? For example, how do I apply str.upper to get:

['THIS IS TEST', 'ANOTHER TEST']

I think you mean to use map instead of filter :

>>> from string import upper
>>> mylis=['this is test', 'another test']
>>> map(upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']

Even simpler, you could use str.upper instead of importing from string (thanks to @alecxe):

>>> map(str.upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, map constructs a new list by applying a given function to every element in a list. filter constructs a new list by restricting to elements that evaluate to True with a given function.

In Python 3.x, map and filter construct iterators instead of lists, so if you are using Python 3.x and require a list the list comprehension approach would be better suited.

Or, alternatively, you can take a list comprehension approach:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

String methods in Python are optimized, so you'll find that the loop implementations mentioned in the other answers here ( 1 , 2 ) to be faster than vectorized methods in other libraries such as pandas and numpy that perform the same task.

In general, you can apply a function to every element in a list using a list comprehension or map() as mentioned in other answers here. For example, given an arbitrary function func , you can either do:

new_list = [func(x) for x in mylis]
# or 
new_list = list(map(func, mylis))

If you want to modify a list in-place , you can replace every element by a slice assignment.

# note that you don't need to cast `map` to a list for this assignment
# this is probably the fastest way to apply a function to a list 
mylis[:] = map(str.upper, mylis)
# or
mylis[:] = [x.upper() for x in mylis]

or with an explicit loop:

for i in range(len(mylis)):
    mylis[i] = mylis[i].upper()

You can also check out the built-in itertools and operator libraries for built-in methods to construct a function to apply to each element. For example, if you want to multiply each element in a list by 2, you can use itertools.repeat and operator.mul :

from itertools import repeat, starmap
from operator import mul

newlis1 = list(map(mul, mylis, repeat(2)))
# or with starmap
newlis2 = list(starmap(mul, zip(mylis, repeat(2))))

# but at this point, list comprehension is simpler imo
newlis3 = [x*2 for x in mylis]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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