Python中常用的幾個內建方法(max()/min()、filter()、map()、sorted、reduce())

python学习者0發表於2024-06-13

1.max()/min()

  • 傳入一個引數 (可迭代物件), 返回這個可迭代物件中最大的元素
    可以設定default關鍵字引數, 當這個可迭代物件為空時, 返回default的值
  • 傳入多個引數, 返回這些引數中最大的引數
    多個引數必須是同型別的
  • 兩種方法都可以設定key關鍵字引數(傳入函式)
"""
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty.
    With two or more arguments, return the largest argument.
"""


res = max([1, 2, 3], default=0)
print(res)  # 3

# 傳入了一個空的可迭代的物件引數, 返回預設值0
res = max([], default=0)
print(res)  # 0



lis = [1, 2, 3]


def func(num):
    return -num


# res = max(lis, key=func)
res = max(lis, key=lambda num: -num)
print(res)  # 1

key引數接收的是一個函式物件
max函式會將lis裡面的元素依次傳入轉換函式
哪個元素經過轉換函式得到的值最大, 就返回該元素

2.filter() 過濾

第一個引數(形參), 要麼是func, 要麼是None, 不傳會報錯

第二個引數是可迭代物件

返回一個filter obj (iterator)

filter()方法會過濾掉:

  • 本身布林值為False的元素
  • 經過函式處理後, 返回值的布林值為False的元素
filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

需要傳入兩個引數, 第一個是函式或者None, 第二個是可迭代物件

返回的是一個filter obj(迭代器)

如果第一個引數時None, 則返回的迭代器中只包含可迭代物件中為True的元素

如果第一引數是一個函式, 可迭代物件中元素傳入該函式, 結果為True, 則filter方法返回的迭代器就會
包含此元素

lis = [0, 1, 2, 3]

filter_obj = filter(None, lis)
print(list(filter_obj))  # [1, 2, 3]


def func(num):
    if num > 1:
        return 0


filter_obj = filter(func, lis)
print(list(filter_obj))  # []

filter_obj = filter(lambda num: num > 1, lis)
print(list(filter_obj))  # [2, 3]

3.map() 對映

第一個引數必須是函式
後面可傳入一個或多個可迭代物件引數

  • 可迭代物件引數的個數, 必須和函式的引數個數相同
  • 多個可迭代物件包含的元素個數不一致, 則以元素個數最少的那個為準
    返回一個map obj (iterator)
"""
    map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.    
"""
    
def func1(x):
    return x + 1


"""
引數1: 函式, 引數2:可迭代物件
1.可迭代物件的中的元素依次傳入函式得到返回值res
2.呼叫map函式最終會得到一個迭代器物件iterator
3. 這個iterator就包含了res
"""

map_obj = map(func1, [1, 2, 3])
print(list(map_obj))  # [2, 3, 4]


def func2(x, y):
    return x + y


"""
傳入的可迭代物件引數個數與函式所需要的引數個數是相等的
取值個數以最短的為準
"""
map_obj = map(func2, [1, 2, 3], [1, 2, 3, 4])
print(list(map_obj))  # [2, 4, 6]

4.sorted篩選

  • 第一個引數是可迭代物件
  • 第二引數是key, 第三個引數是reverse, 這兩個引數可不傳
"""
	sorted(iterable, key, reverse) --> list
	
    Return a new list containing all items from the iterable in ascending order.
    A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
"""
lis = [3, 2, 4, 5, 1]

# 1.只傳入可迭代物件引數
res = sorted(lis)
print(res)  # [1, 2, 3, 4, 5]


def func(x):
    return -x

#2.當傳入函式時, 可迭代物件元素排序的依據是他們傳入函式得到結果
#注意: 還是對原來的元素進行排序, 而不是對元素傳入函式得到的結果, 只是以這個結果為排序的依據

res = sorted(lis, key=func)
print(res)  # [5, 4, 3, 2, 1]

5.reduce()減少

  • 第一個引數是函式:該函式必須是有且只有兩個引數
  • 第二個引數是序列
  • initial是初始值, 可以當做序列的第一個元素
  • 這個reduce指的是不斷減少的是序列中的元素個數, 直到序列只剩下一個元素, 返回該元素
from functools import reduce

"""
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).  
    If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
"""
#學習中遇到問題沒人解答?小編建立了一個Python學習交流群:153708845

lis = [1, 2, 3, 4, 5]
res1 = reduce(lambda x, y: x + y, lis)
print(res1)  # 15

res2 = reduce(lambda x, y: x + y, lis, 1)
print(res2)  # 16

相關文章