Warm tip: This article is reproduced from serverfault.com, please click

Apply function to each element of a list

发布于 2014-08-01 14:25:16

How do I apply a function to the list of variable inputs? For e.g. the filter function returns true values but not the actual output of the function.

from string import upper
mylis=['this is test', 'another test']

filter(upper, mylis)
['this is test', 'another test']

The expected output is :

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

I know upper is built-in. This is just an example.

Questioner
shantanuo
Viewed
0
261k 2014-08-01 23:06:37

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.