在 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', 'zadmei', 'com']
for index, item in enumerate(my_list):
print(index, item) # 👉️ 0 fql, 1 zadmei, 2 com
在每次迭代中,我们将当前索引处的项目重新分配给使用该项目调用函数的结果。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。