首页 > 编程语言 >python3常用内置函数及常用库functools使用

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

时间:2024-10-09 16:35:02浏览次数:1  
标签:常用 函数 functools list colors def print python3

常用内置函数

# 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]

 

标签:常用,函数,functools,list,colors,def,print,python3
From: https://www.cnblogs.com/caroline2016/p/18454575

相关文章

  • python3常用库之哈希hashlib和hmac使用
    hashlibimporthashlib#MD5是最常见的哈希算法,速度很快,生成结果是固定的128bit/16字节,通常用一个32位的16进制字符串表示。md5=hashlib.md5()md5.update("hello".encode())print(md5.hexdigest())#5d41402abc4b2a76b9719d911017c592#数据量很大时分块多次调用up......
  • python3常用库之collections集合库
    namedtuple#namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。#用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用Coord=collections.namedtuple("Coord",["......
  • python3常用库之datetime库
    日期时间fromdatetimeimportdatetime,timedelta,timezonenow=datetime.now()print(now)#2024-02-0214:27:12.247121dt=datetime(2023,12,31,12,30,00)print(dt)#2023-12-3112:30:00#时间戳,和时区无关ts=dt.timestamp()print(ts)#17039970......
  • python3常用库之解析命令行参数argparse
    在命令行程序中需要获取命令行参数可以使用sys库和argparse库。sys库可用于处理简单的命令行参数,argparse库可用于处理复杂的命令行参数。#argparse解析命令行参数importargparse,sysdefmain():#定义一个ArgumentParser实例:参数分别为程序名、描述、说明信息......
  • python3常用库之Base64编码
    Base64是一种用64个字符来表示任意二进制数据的方法。importbase64by="abc中文".encode()b=base64.b64encode(by)print(by)#b'abc\xe4\xb8\xad\xe6\x96\x87'print(b)#b'YWJj5Lit5paH'by2=base64.b64decode(b)print(by2)#b'abc\xe......
  • pandas常用数据格式IO性能对比
    前言本文对pandas支持的一些数据格式进行IO(读写)的性能测试,大数据时代以数据为基础,经常会遇到操作大量数据的情景,数据的IO性能尤为重要,本文对常见的数据格式csv、feather、hdf5、jay、parquet、pickle性能进行对比。csvCSV(Comma-SeparatedValues)是一种用于存储表格数据的......
  • Hive(五)常用函数
    Hive常用函数字符串函数返回值函数描述stringconcat(string/binaryA,string/binaryB…)对二进制字节码或字符串按次序进行拼接intinstr(stringstr,stringsubstr)查找字符串str中子字符串substr出现的位置intlength(stringA)返回字符串的长度int......
  • js常用校验规则
    一、校验数字的js正则表达式1数字:[1]$2n位的数字:^\d{n}$3至少n位的数字:^\d{n,}$4m-n位的数字:^\d{m,n}$5零和非零开头的数字:^(0|[1-9][0-9])$6非零开头的最多带两位小数的数字:^([1-9][0-9])+(.[0-9]{1,2})?$7带1-2位小数的正数或负数:^(-)?\d+(.\d{1,2})?$8正数、负......
  • js常用校验规则2
    1.1、校验是否为空(null/空串)/*校验是否为空(null/空串)*/varcheckNull=function(str){if(str==null||str==""){returnfalse;}returntrue;}1.2、校验是否为纯数字/*校验是否为纯数字js的isNaN函数*/varcheckNum=function(num){if(isNaN(num)){......
  • Git常用操作
    Git:分布式版本控制系统。工作原理和流程图:Workspace:工作区Index/Stage:暂存区Repository:仓库区Remote:远程仓库gitconfig--global参数:gitconfig--globaluser.namegitconfig--globaluser.email创建仓库:repository,简答的理解为一个目录mkdirtestgit2.......