将函数应用于列表的每个元素 [英] Apply function to each element of a list
问题描述
如何将函数应用于变量输入列表?
例如过滤器
函数返回真值,但不是函数的实际输出。
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']
我知道 upper
是内置的。这只是一个例子。
I know upper
is built-in. This is just an example.
推荐答案
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']
更简单的话,你可以使用 str.upper
而不是从 string
进行导入(感谢@alecxe) p>
Even simpler, you could use str.upper
instead of importing from string
(thanks to @alecxe):
>>> map(str.upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']
在Python 2.x中, map
通过将给定的函数应用于列表中的每个元素来构造一个新列表。 filter
通过限制元素的结构来限制使用给定函数计算 True
的元素。
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.
在Python 3.x中, map
和 filter
构造迭代器而不是列表,所以如果你使用的是Python 3.x并且需要一个列表,那么list-comprehension方法会更适合。
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.
这篇关于将函数应用于列表的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!