Python 将函数应用于列表的每个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25082410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:42:17  来源:igfitidea点击:

Apply function to each element of a list

pythonlistfunction

提问by shantanuo

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

如何将函数应用于变量输入列表?例如,filter函数返回真值而不是函数的实际输出。

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 upperis built-in. This is just an example.

我知道upper是内置的。这只是一个例子。

采纳答案by mdml

I think you mean to use mapinstead of filter:

我认为您的意思是使用map而不是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.upperinstead of importing from string(thanks to @alecxe):

更简单的是,您可以使用str.upper而不是从导入string(感谢@alecxe):

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

In Python 2.x, mapconstructs a new list by applying a given function to every element in a list. filterconstructs a new list by restricting to elements that evaluate to Truewith a given function.

在 Python 2.x 中,map通过将给定函数应用于列表中的每个元素来构造一个新列表。filter通过限制对True给定函数求值的元素来构造一个新列表。

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

在Python 3.x中,mapfilter构建迭代器,而非列表,所以如果你使用Python 3.x和要求的清单列表解析的方法会更适合。

回答by alecxe

Or, alternatively, you can take a list comprehensionapproach:

或者,您可以采取一种list comprehension方法:

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