python内置函数 - map, reduce, filter, sort

发布时间 2023-09-04 23:31:03作者: yanghui01

1, map(fn, 可迭代对象)

参数fn为一个参数的函数

lambda方式

my_list = [2, 3, 4, 5]
result = map(lambda x: x * x, my_list) # 返回元素平方值的迭代器
print(type(result)) # <class 'map'>
print(isinstance(result, collections.abc.Iterator)) # True

new_list = list(result)
print(new_list) # [4, 9, 16, 25]

 

 def函数方式

def my_sqrt(x):
    return x * x

my_list = [2, 3, 4, 5]

iterator = map(my_sqrt, my_list)
print(type(iterator)) # <class 'map'>

new_list = list(iterator)
print(new_list) # [4, 9, 16, 25]

 

2, reduce(fn, 可迭代对象)

参数fn为2个参数的函数

from functools import reduce

my_list = [2, 3, 4]
init_value = 1
result = reduce(lambda x, y: x + y, my_list, init_value)
print(type(result)) # <class 'int'>
print(result) # 10: 1+2+3+4

 

3, filter(fn, 可迭代对象)

参数fn为1个参数的函数, 返回bool类型

my_list = [1, 2, 3, 4]
result = filter(lambda x:x%2==0, my_list) # 返回偶数迭代器
print(type(result)) # <class 'filter'>
print(isinstance(result, collections.abc.Iterator)) # True

new_list = list(result)
print(new_list) # [2, 4]

 

4, sorted(可迭代对象, key=fn)

参数key为1个参数的函数

my_list = ['aa', 'b', 'ccc']
result = sorted(my_list, key=lambda x:len(x))
print(type(result)) # <class 'list'>
print(isinstance(result, collections.abc.Iterator)) # True
print(result) # ['b', 'aa', 'ccc']

result = sorted(my_list)
print(result) # ['aa', 'b', 'ccc']

 

参考

Python中的map()函数 - 简书 (jianshu.com)

python——lambda函数_python lambda函数_PL C的博客-CSDN博客

Python中的sorted函数 - 知乎 (zhihu.com)