简体   繁体   English

将 function 应用于列表的每个元素

[英]Apply function to each element of a list

Suppose I have a list like:假设我有一个像这样的列表:

mylis = ['this is test', 'another test']

How do I apply a function to each element in the list?如何将 function 应用于列表中的每个元素? For example, how do I apply str.upper to get:例如,我如何应用str.upper来获得:

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

I think you mean to use map instead 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.upper instead of importing from string (thanks to @alecxe):更简单的是,您可以使用str.upper而不是从string导入(感谢@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.在 Python 2.x 中, map通过将给定函数应用于列表中的每个元素来构造一个新列表。 filter constructs a new list by restricting to elements that evaluate to True with a given function. filter通过限制使用给定函数评估为True的元素来构造一个新列表。

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.在 Python 3.x 中, mapfilter构造迭代器而不是列表,因此如果您使用 Python 3.x 并需要列表,则列表推导方法会更适合。

Or, alternatively, you can take a list comprehension approach:或者,或者,您可以采用列表理解方法:

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

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请注意, map()的输出被传递给列表构造函数,以确保列表在 Python 3 中被转换。应该忽略填充为None值的返回列表,因为我们的目的是就地转换列表a

String methods in Python are optimized, so you'll find that the loop implementations mentioned in the other answers here ( 1 , 2 ) to be faster than vectorized methods in other libraries such as pandas and numpy that perform the same task. Python 中的字符串方法经过优化,因此您会发现此处其他答案( 1、2 )中提到的循环实现比执行相同任务的其他库(例如 pandas 和numpy )中的矢量化方法更快。

In general, you can apply a function to every element in a list using a list comprehension or map() as mentioned in other answers here.通常,您可以使用列表理解或map()将 function 应用于列表中的每个元素,如其他答案中所述。 For example, given an arbitrary function func , you can either do:例如,给定一个任意的 function func ,你可以这样做:

new_list = [func(x) for x in mylis]
# or 
new_list = list(map(func, mylis))

If you want to modify a list in-place , you can replace every element by a slice assignment.如果你想就地修改列表,你可以用切片分配替换每个元素。

# note that you don't need to cast `map` to a list for this assignment
# this is probably the fastest way to apply a function to a list 
mylis[:] = map(str.upper, mylis)
# or
mylis[:] = [x.upper() for x in mylis]

or with an explicit loop:或者使用显式循环:

for i in range(len(mylis)):
    mylis[i] = mylis[i].upper()

You can also check out the built-in itertools and operator libraries for built-in methods to construct a function to apply to each element.您还可以查看内置的itertools运算符库,以了解构建 function 以应用于每个元素的内置方法。 For example, if you want to multiply each element in a list by 2, you can use itertools.repeat and operator.mul :例如,如果你想将列表中的每个元素乘以 2,你可以使用itertools.repeatoperator.mul

from itertools import repeat, starmap
from operator import mul

newlis1 = list(map(mul, mylis, repeat(2)))
# or with starmap
newlis2 = list(starmap(mul, zip(mylis, repeat(2))))

# but at this point, list comprehension is simpler imo
newlis3 = [x*2 for x in mylis]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM