searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

python中函数传递列表元素的8种方法(4)

2024-11-22 17:35:03
0
0

使用 `map` 函数: 对列表中每个元素应用同一函数。

def square(x):
    """计算平方"""
    return x * x

my_list = [1, 2, 3]
squared_list = list(map(square, my_list)) # 使用map函数,对每个元素应用square函数
print(squared_list)  # 输出: [1, 4, 9]

使用 `filter` 函数: 根据条件过滤列表元素。

def is_even(x):
    """判断是否为偶数"""
    return x % 2 == 0

my_list = [1, 2, 3, 4]
even_numbers = list(filter(is_even, my_list))  # filter过滤出符合条件的元素
print(even_numbers) # 输出: [2, 4]

0条评论
0 / 1000
王****际
180文章数
2粉丝数
王****际
180 文章 | 2 粉丝
原创

python中函数传递列表元素的8种方法(4)

2024-11-22 17:35:03
0
0

使用 `map` 函数: 对列表中每个元素应用同一函数。

def square(x):
    """计算平方"""
    return x * x

my_list = [1, 2, 3]
squared_list = list(map(square, my_list)) # 使用map函数,对每个元素应用square函数
print(squared_list)  # 输出: [1, 4, 9]

使用 `filter` 函数: 根据条件过滤列表元素。

def is_even(x):
    """判断是否为偶数"""
    return x % 2 == 0

my_list = [1, 2, 3, 4]
even_numbers = list(filter(is_even, my_list))  # filter过滤出符合条件的元素
print(even_numbers) # 输出: [2, 4]

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0