Apply function to each element of a list

后端 未结 3 1848
花落未央
花落未央 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:21

    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

提交回复
热议问题