将函数应用于列表的每个元素[重复]
- 2024-12-16 08:35:00
- admin 原创
- 145
问题描述:
假设我有一个如下列表:
mylis = ['this is test', 'another test']
如何将函数应用于列表中的每个元素?例如,如何应用str.upper
以获取:
['THIS IS TEST', 'ANOTHER TEST']
解决方案 1:
尝试使用列表推导:
>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']
解决方案 2:
使用内置标准库map
:
>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']
在 Python 2.x 中,map
通过将给定函数应用于列表中的每个元素来构建所需的新列表。
在 Python 3.x 中,map
构造迭代器而不是列表,因此list
需要调用。如果您使用的是 Python 3.x 并且需要列表,则列表推导方法会更适合。
解决方案 3:
有时你需要将函数应用于列表的成员。以下代码对我有用:
>>> 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']
请注意, map()的输出被传递给列表构造函数,以确保列表在 Python 3 中转换。返回的填充None值的列表应该被忽略,因为我们的目的是就地转换列表a
解决方案 4:
Python 中的字符串方法经过了优化,因此您会发现这里其他答案中提到的循环实现(1、2 )比执行相同任务的其他库(如 pandas 和 numpy)中的矢量化方法更快。
通常,您可以使用列表推导将函数应用于列表中的每个元素,或者map()
如此处其他答案中所述。例如,给定一个任意函数func
,您可以执行以下操作:
new_list = [func(x) for x in mylis]
# or
new_list = list(map(func, mylis))
如果您想就地修改列表,您可以通过切片分配替换每个元素。
# 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]
或者使用显式循环:
for i in range(len(mylis)):
mylis[i] = mylis[i].upper()
您还可以查看内置的itertools和运算符库,以获取内置方法来构造一个应用于每个元素的函数。例如,如果您想将列表中的每个元素乘以 2,则可以使用itertools.repeat
and operator.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]
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD