python3常用内置函数及常用库functools使用

常用内置函数

# lambda 函数 -----------------------------
add = lambda a, b, c: a + b + c
print(add(1, 2, 3))  # 6


# sorted 函数 -----------------------------
a_l = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
print(sorted(a_l))  # [-9, -5, -4, -1, 0, 1, 3, 5, 7, 8]
print(sorted(a_l, reverse=True))  # [8, 7, 5, 3, 1, 0, -1, -4, -5, -9]

# 字典按照value的顺序排序
colors_d = {"red": 2, "yellow": 4, "green": 1, "black": 3}
print(dict(sorted(colors_d.items(), key=lambda item: item[1])))  # {'green': 1, 'red': 2, 'black': 3, 'yellow': 4}

# 字典按照key的顺序排序
print(dict(sorted(colors_d.items(), key=lambda item: item[0])))  # {'black': 3, 'green': 1, 'red': 2, 'yellow': 4}


# map 函数 --------------------------------
def makeupper(word):
    return word.upper()


colors = ["red", "yellow", "green", "black"]
colors_upper = list(map(makeupper, colors))
print(colors_upper)  # ['RED', 'YELLOW', 'GREEN', 'BLACK']

print(list(map(lambda x: x.upper(), colors)))  # ['RED', 'YELLOW', 'GREEN', 'BLACK']

a = [1, 3, 5]
b = [2, 4, 6]
print(list(map(lambda x, y: x + y, a, b)))  # [3, 7, 11]


# filter函数  --------------------------------
# filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新序列


def great_then_0(x):
    return x > 0


print(list(filter(great_then_0, a_l)))  # [1, 3, 5, 7, 8]

print(list(filter(lambda x: x > 0, a)))  # [1, 3, 5, 7, 8]

print(dict(filter(lambda x: x[1] > 3, colors_d.items())))  # {'yellow': 4}


# enumerate函数 --------------------------------
# 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中
result = enumerate(colors)
for i, j in result:
    print(i, j)  # 0 red 1 yellow  ...


# zip函数
# zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
colors = ["red", "yellow", "green", "black"]
fruits = ["apple", "pineapple", "grapes", "cherry"]
for item in zip(colors, fruits):
    print(item)  # ('red', 'apple')  ('yellow', 'pineapple') ...

print(dict(zip(colors, fruits)))  # {'red': 'apple', 'yellow': 'pineapple', 'green': 'grapes', 'black': 'cherry'}
print(list(zip(colors, fruits)))  # {'red': 'apple', 'yellow': 'pineapple', 'green': 'grapes', 'black': 'cherry'}

functools.partial 

偏函数, 创建一个具有固定参数的函数

import functools


def power(base, exponent):
    return base**exponent


# 偏函数, 创建一个具有固定参数的函数
square = functools.partial(power, exponent=2)
print(square(3))  # 9

functools.lru_cache 、functools.cache装饰器

装饰器用于缓存函数的返回值,这对于避免重复计算昂贵的函数调用非常有用
# lru_cache 装饰器用于缓存函数的返回值,这对于避免重复计算昂贵的函数调用非常有用
@functools.lru_cache(maxsize=None)
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)


@functools.cache
def fact(n):
    if n == 0:
        return 1
    return n * fact(n - 1)


print(fib(100))  # 354224848179261915075
print(fact(10))  # 3628800

functools.reduce

累积计算

def multiply(x, y):
    return x * y


def add(*args):
    result = 0
    for i in args:
        result += i
    return result


# reduce 累积计算
print(functools.reduce(multiply, [1, 2, 3, 4]))

L = list(range(1, 101))
print(functools.reduce(add, L))  # 5050

print(functools.reduce(lambda x, y: x + y, L))  # 5050

print(functools.reduce(lambda x, y: y + x, "ABCDE"))  # EDCBA

 functools.cmp_to_key

函数用于将比较函数(接受两个参数并返回负数、零或正数的函数)转换为关键函数,以便用于排序操作。

def compare_len(s1, s2):
    return len(s1) - len(s2)


# functools.cmp_to_key函数用于将比较函数(接受两个参数并返回负数、零或正数的函数)转换为关键函数,以便用于排序操作。
sorted_l = sorted(["apple", "pear", "banana"], key=functools.cmp_to_key(compare_len))
print(sorted_l)  # ['pear', 'apple', 'banana']

functools.total_ordering

total_ordering是一个装饰器,它为类定义了一些特殊方法,以便使用比较操作符(如<、<=、>、>=)进行对象比较。
# functools.total_ordering是一个装饰器,它为类定义了一些特殊方法,以便使用比较操作符(如<、<=、>、>=)进行对象比较。
@functools.total_ordering
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other: object) -> bool:
        return self.age == other.age

    def __lt__(self, other: object) -> bool:
        return self.age < other.age


p1 = Person("aa", 20)
p2 = Person("bb", 18)

print(p1 == p2)  # False
print(p1 > p2)  # True

functools.singledispatch

泛型函数,根据函数基本类型形参调用不同的函数

# 泛型函数,根据函数基本类型形参调用不同的函数
@functools.singledispatch
def myfunc(arg):
    print("func default {}".format(arg))


@myfunc.register(int)
def myfunc_int(arg):
    print("func int", arg)


@myfunc.register(list)
def myfunc_list(arg):
    print("func list", arg)


myfunc("hello")  # func default hello
myfunc(1)  # func int 1
myfunc(2.3)  # func default 2.3
myfunc([1, 2])  # func list [1, 2]

 

posted @   carol2014  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示