Apply function to each element of a list

后端 未结 3 1776
花落未央
花落未央 2020-11-29 23:40

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.

         


        
3条回答
  •  有刺的猬
    2020-11-30 00:10

    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.

提交回复
热议问题