在 Python 中将函数应用于列表的每个元素
Python 中将函数应用于列表的每个元素:
- 使用列表理解来遍历列表。
- 在每次迭代中使用当前列表项调用该函数。
- 新列表将包含将函数应用于原始列表的每个元素的结果。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
new_list = [increment(item) for item in a_list]
# 👇️ [4, 5, 9, 12]
print(new_list)
我们使用列表推导来迭代列表。
列表推导用于对每个元素执行一些操作,或者选择满足条件的元素子集。
在每次迭代中,我们使用当前列表项调用 increment()
函数并返回结果。
新列表包含将函数应用于原始列表的每个元素的结果。
如果我们不必保留原始列表,请重新分配变量。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
# ✅ reassign variable instead of declaring a new one
a_list = [increment(item) for item in a_list]
# 👇️ [4, 5, 9, 12]
print(a_list)
如果我们只需要将函数应用于特定的列表元素,我们也可以使用 if/else
子句。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
a_list = [
increment(item) if item > 4 else item
for item in a_list
]
# 👇️ [3, 4, 9, 12]
print(a_list)
如果列表项大于 4,则代码示例仅将该函数应用于列表项。
我们还可以使用 map()
函数将函数应用于列表的每个元素。
使用 map() 将函数应用于列表的每个元素
将函数应用于列表的每个元素:
-
将函数和列表传递给
map()
函数。 -
map()
函数将对每个列表项调用提供的函数。 -
使用
list()
类将地图对象转换为列表。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
new_list = list(map(increment, a_list))
print(new_list) # 👉️ [4, 5, 9, 12]
map()
函数将一个函数和一个可迭代对象作为参数,并使用可迭代对象的每个项目调用该函数。
我们作为第一个参数传递给
map()
的函数被每个列表项调用。
最后一步是使用 list()
类将地图对象转换为列表。
列表类接受一个可迭代对象并返回一个列表对象。
我们可能还会在网上看到使用 lambda 函数的示例。
a_list = [3, 4, 8, 11]
new_list = list(map(lambda x: x + 1, a_list))
print(new_list) # 👉️ [4, 5, 9, 12]
Lambda 函数是匿名的内联函数,当函数必须执行的操作相对简单时使用。
示例中的 lambda
接受单个参数 x 并返回 x + 1
。
或者,我们可以使用简单的 for 循环。
使用 for 循环将函数应用于列表的每个元素
将函数应用于列表的每个元素:
-
使用
for
循环遍历列表。 - 在每次迭代中,使用当前列表项调用该函数。
- 将结果附加到新列表。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
new_list = []
for item in a_list:
new_list.append(increment(item))
print(new_list) # 👉️ [4, 5, 9, 12]
我们使用 for
循环遍历列表。
在每次迭代中,我们使用当前列表项调用该函数并将结果附加到新列表。
list.append()
方法将一个项目添加到列表的末尾。
如果我们想就地更改列表而不是创建新列表,请使用 enumerate()
函数。
def increment(x):
return x + 1
a_list = [3, 4, 8, 11]
for index, item in enumerate(a_list):
a_list[index] = increment(item)
print(a_list) # 👉️ [4, 5, 9, 12]
enumerate
函数接受一个可迭代对象并返回一个包含元组的枚举对象,其中第一个元素是索引,第二个元素是相应的项目。
my_list = ['fql', 'jiyik', 'com']
for index, item in enumerate(my_list):
print(index, item) # 👉️ 0 fql, 1 jiyik, 2 com
在每次迭代中,我们将当前索引处的项目重新分配给使用该项目调用函数的结果。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中使用 stack() 和 unstack() 函数重塑 DataFrame
发布时间:2024/04/24 浏览次数:1289 分类:Python
-
本文讨论了 Pandas 中 stack() 和 unstack() 函数的使用。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。