python常用函数汇总

python常用函数汇总

对准蓝字按下左键可以跳转哦

类型 函数
数值相关函数 abs() divmod() max() min() pow() round() sum()
类型转换函数 ascii() bin() hex() oct() bool() bytearray() bytes() chr() complex() float() int()
迭代和循环函数 iter() next() enumerate() reversed() sorted()
容器和集合函数 all() any() len() list() set() tuple() dict() frozenset()
字符串和字符处理函数 format() str() ord() repr()
文件和输入输出函数 open() input() print()
错误和异常处理函数 breakpoint() eval() exec() globals() locals() compile() import()
属性和对象操作函数 getattr() hasattr() setattr() delattr() id() isinstance() issubclass() property() vars()
其他函数 callable() classmethod() staticmethod() hash() help() memoryview()
高阶函数 map() zip() filter()

数值相关函数

abs() divmod() max() min() pow() round() sum()

abs()

返回一个数的绝对值

num = -5
result = abs(num)
print(result)  # 输出: 5

divmod()

接受两个数字类型参数,并且返回两数的商和余

num1 = 20
num2 = 3
result1, result2 = divmod(num1, num2 )
print(result1)    # 输出: 6
print(result2)   # 输出: 2

max()

接受一个可迭代参数,返回其中的最大值

num = [4, 8, 2, 1, 9]
min_mum = min(num)
print(min_mum)  # 输出: 9

min()

接受一个可迭代参数,返回其中的最小值

num = [4, 8, 2, 1, 9]
min_mum = min(num)
print(min_mum)  # 输出: 1

pow()

接受一个数字类型,计算出它的指数幂

base = 2
exponent = 3
result = pow(base, exponent)
print(result)  # 输出: 8

round()

接受一个浮点数,返回一个四舍五入后的指定位数的小数

number = 3.14159
rounded = round(number, 2)
print(rounded)  # 输出: 3.14

sum()

接受一个由整数组成的可迭代对象,计算其中所有元素的和

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # 输出: 15

类型转换函数

ascii() bin() hex() oct() bool() bytearray() bytes() chr() complex() float() int()

ascii()

返回一个表示对象的字符串,使用 ASCII 编码

text = "Hello, 你好"
result = ascii(text)
print(result)  # 输出: 'Hello, \u4f60\u597d'

bin()

将一个整数转换成二进制字符串

number = 10
binary = bin(number)
print(binary)  # 输出: '0b1010'

hex()

将一个整数转换成十六进制字符串

number = 15
hex_string = hex(number)
print(hex_string)  # 输出: '0xf'

oct()

将一个整数转换为八进制字符串

number = 8
octal_string = oct(number)
print(octal_string)  # 输出: '0o10'

bool()

将给定的值转换为布尔类型

value1 = 0
value2 = ""
value3 = []
print(bool(value1))  # 输出: False
print(bool(value2))  # 输出: False
print(bool(value3))  # 输出: False

bytearray()

返回一个可变的字节数组对象

text = "Hello"
byte_array = bytearray(text, "utf-8")
print(byte_array)  # 输出: bytearray(b'Hello')

bytes()

返回一个不可变的字节对象

text = "Hello"
byte_string = bytes(text, "utf-8")
print(byte_string)  # 输出: b'Hello'

chr()

返回指定 Unicode 码位的字符

unicode_value = 65
character = chr(unicode_value)
print(character)  # 输出: 'A'

complex()

创建一个复数对象

real = 2
imaginary = 3
complex_num = complex(real, imaginary)
print(complex_num)  # 输出: (2+3j)

float()

将一个数字或字符串转换为浮点数

number_str = "3.14"
float_num = float(number_str)
print(float_num)  # 输出: 3.14

int()

函数用于将一个数字或字符串转换为整数

number_str = "10"
integer = int(number_str)
print(integer)  # 输出: 10

迭代和循环函数

iter()next()enumerate()reversed()sorted()

iter()

接受一个可迭代类型数据,返回一个迭代器对象

numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)

print(next(iterator))  # 输出: 1
print(next(iterator))  # 输出: 2
print(next(iterator))  # 输出: 3

next()

从迭代器中获取下一个元素,如果没有更多元素则引发StopIteration异常

numbers = [1, 2, 3]
iterator = iter(numbers)

print(next(iterator))  # 输出: 1
print(next(iterator))  # 输出: 2
print(next(iterator))  # 输出: 3
print(next(iterator))  # 引发 StopIteration 异常

enumerate()

接受一个可迭代对象,返回它的元素和索引

fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(index, fruit)
    
# 输出:
# 0 apple
# 1 banana
# 2 orange

reversed()

反转一个序列元素,并且返回一个迭代器

numbers = [1, 2, 3, 4, 5]
reversed_numbers = reversed(numbers)

for num in reversed_numbers:
    print(num)
    
# 输出:
# 5
# 4
# 3
# 2
# 1

sorted()

接受一个可迭代对象对其排序,并且返回一个新的已排序列表

numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers)

print(sorted_numbers)  # 输出: [1, 2, 3, 4, 5]

容器和集合函数

all()any()len()list()set()tuple()dict()frozenset()

all()

用于判断可迭代对象中的所有元素是否都为真,任意为假返回False

numbers = [2, 4, 6, 8, 10]
result = all(num % 2 == 0 for num in numbers)
print(result)  # 输出: True

any()

用于判断可迭代对象中的所有元素是否存在真,任意为真返回True

numbers = [1, 2, 3, 4, 5]
result = any(num % 2 == 0 for num in numbers)
print(result)  # 输出: True

len()

计算元素长度

text = "Hello"
length = len(text)
print(length)  # 输出: 5

numbers = [1, 2, 3, 4, 5]
count = len(numbers)
print(count)  # 输出: 5

list()

接受一个可迭代对象将其转换成列表

numbers = (1, 2, 3, 4, 5)
number_list = list(numbers)
print(number_list)  # 输出: [1, 2, 3, 4, 5]

set()

接受一个可迭代对象将其转换成集合

numbers = [1, 2, 3, 2, 4, 5, 1]
unique_numbers = set(numbers)
print(unique_numbers)  # 输出: {1, 2, 3, 4, 5}

tuple()

接受一个可迭代对象将其转换成元组

numbers = [1, 2, 3, 4, 5]
number_tuple = tuple(numbers)
print(number_tuple)  # 输出: (1, 2, 3, 4, 5)

dict()

接受一个可迭代对象将其转换成字典

student = dict(name="Alice", age=20, grade="A")
print(student)  # 输出: {'name': 'Alice', 'age': 20, 'grade': 'A'}

frozenset()

冻结一个集合对象,返回一个新的不可变对象,但是原对象可以被修改

numbers = [1, 2, 3, 2, 4, 5, 1]
frozen_numbers = frozenset(numbers)
numbers.append(7)
print(numbers)  # [1, 2, 3, 2, 4, 5, 1, 7]
print(frozen_numbers)  # 输出: frozenset({1, 2, 3, 4, 5})

# frozen_numbers.append(1)  # 报错AttributeError: 'frozenset' object has no attribute 'append'

字符串和字符处理函数

format()str()ord()repr()

format()

格式化数据

import datetime

# 格式化数字:
number = 3.14159
formatted = format(number, ".2f")
print(formatted)  # 输出: "3.14"

# 指定填充字符和对齐方式:
text = "Hello"
formatted = format(text, "^10")
print(formatted)  # 输出: "  Hello   "

# 使用关键字参数进行格式化:
name = "Alice"
age = 25
result = format("My name is {}, and I'm {} years old.".format(name, age))
print(result)  # 输出: "My name is Alice, and I'm 25 years old."

# 使用索引进行格式化:
values = ("Alice", 25)
result = format("My name is {0}, and I'm {1} years old.", *values)
print(result)  # 输出: "My name is Alice, and I'm 25 years old."

# 格式化日期时间:
now = datetime.datetime.now()
formatted = format(now, "%Y-%m-%d %H:%M:%S")
print(formatted)  # 输出: "2023-12-24 10:30:00"

str()

将参数转换成字符串

number = 10
text = str(number)
print(text)  # 输出: "10"

ord()

返回一个字符的 Unicode 数值

character = 'A'
unicode_value = ord(character)
print(unicode_value)  # 输出: 65

repr()

返回一个对象的字符串表示形式,通常用于调试和显示对象

number = 10
representation = repr(number)
print(representation)  # 输出: "10"

文件和输入输出函数

open()input()print()

open()

打开文件并返回一个文件对象,可用于读写操作

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

input()

获取用户输入的数据,并且返回字符串

name = input("请输入您的姓名:")
age = input("请输入您的年龄:")
print(f"您好,{name},您的年龄是{age}岁。")

print()

打印数据

name = "Alice"
age = 25
print("My name is", name, "and I'm", age, "years old.")

错误和异常处理函数

breakpoint()eval()exec()globals()locals()compile()import()

breakpoint()

在代码中设置调试断点,启动调试器

def divide(a, b):
    result = a / b
    breakpoint()  # 设置调试断点
    return result

divide(10, 2)

eval()

动态执行字符串中的python代码,并返回结果

expression = "2 + 3 * 4"
result = eval(expression)
print(result)  # 输出: 14

exec()

动态执行字符串中的python代码,且支持多行判定

code = """
for i in range(5):
    print(i)
"""
exec(code)

globals()

以字典形式返回当前模块的全局变量

name = "Anna"


def my_function():
    print(globals())


my_function()
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001E446205F50>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'D:\\Users\\Desktop\\LnhStudy\\Day25\\trst04.py', '__cached__': None, 'name': 'Anna'
								^
    							|
#        					 Anna在这

locals()

字典形式返回当前模块的局部变量

def my_function():
    x = 10
    print(locals())


my_function()  # {'x': 10}

compile()

将参数编译,可以搭配exec()使用

source_code = "print('Hello, World!')"
compiled_code = compile(source_code, "", "exec")
exec(compiled_code)
# Hello, World!

__import__()

在函数运行时动态的导入模块,和import类似

module_name = "math"	# 导入math模块
module = __import__(module_name)
result = module.sqrt(16) # 计算16的平方根
print(result)  # 输出: 4.0

属性和对象操作函数

getattr()hasattr()setattr()delattr()id()isinstance()issubclass()property()vars()

getattr()

获取对象的属性值

class Person:
    name = "Alice"

person = Person()
result = getattr(person, "name")
print(result)  # 输出: "Alice"

hasattr()

用于检查对象是否具有指定属性

class Person:
    name = "Alice"

person = Person()
result = hasattr(person, "age")
print(result)  # 输出: False

setattr()

用于设置对象的属性值

class Person:
    name = ""

person = Person()
setattr(person, "name", "Alice")
print(person.name)  # 输出: "Alice"

delattr()

用于删除对象的属性

class Person:
    name = "Alice"

person = Person()
delattr(person, "name")
print(hasattr(person, "name"))  # 输出: False

id()

返回对象的唯一标识

person = "Alice"
identity = id(person)
print(identity)  # 输出: 3030971146224

isinstance()

检查对象是否属于指定类型

numbers = [1, 2, 3]
result = isinstance(numbers, list)
print(result)  # 输出: True

issubclass()

检查对象是否是另一个类的子类

class Animal:
    pass

class Dog(Animal):
    pass

result = issubclass(Dog, Animal)
print(result)  # 输出: True

property()

定义属性访问器

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value > 0:
            self._radius = value
        else:
            raise ValueError("Radius must be greater than 0.")

circle = Circle(5)
print(circle.radius)  # 输出: 5

circle.radius = 10
print(circle.radius)  # 输出: 10

vars()

返回对象的属性和属性值的字典

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)
result = vars(person)
print(result)  # 输出: {'name': 'Alice', 'age': 25}

其他函数

callable()classmethod()staticmethod()hash()help()memoryview()#t)

callable()

检查对象是否可调用

def my_function():
    print("Hello, World!")

result = callable(my_function)
print(result)  # 输出: True

classmethod()

classmethod()是一个装饰器,用于定义类方法,类方法是绑定到类而不是实例的方法

class Person:
    name = "Alice"

    @classmethod
    def get_name(cls):
        return cls.name

result = Person.get_name()
print(result)  # 输出: "Alice"

staticmethod()

staticmethod()是一个装饰器,用于定义新的静态方法,静态方法与类和示例无关,相当于普通函数,但在类内部定义

class Calculator:
    @staticmethod
    def add(a, b):
        return a + b

result = Calculator.add(3, 5)
print(result)  # 输出: 8

hash()

返回对象的哈希值,用于在哈希表中快速定位元素

number = '42'
hash_value = hash(number)
print(hash_value)  # 6391978310865315419

help()

获取函数、模块或对象的帮助信息

import math

help(math.sqrt)

memoryview()

创建一个内存视图对象,可用于对底层数据进行高级操作

numbers = [1, 2, 3, 4, 5]
byte_array = bytearray(numbers)	# 先转换为字节数组否则会报错
mem_view = memoryview(byte_array)

print(mem_view[0])  # 输出: 1
print(mem_view[1])  # 输出: 2

python高阶函数

map()zip()filter()

map()

将指定函数应用于可迭代对象中的每个元素,并返回包含结果的迭代器

num = [1, 2, 3, 4, 5]


def func(num):
    return num * 2


new_num = map(func, num) # 注意func不能加括号
for i in new_num:
    print(i)
# 2 4 6 8 10

同样适用于lambda表达式,并且可以通过list强转再输出

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared))  # 输出: [1, 4, 9, 16, 25]

zip()

将多个可迭代对象进行元素配对,并返回包含结果的迭代器

num = [1, 2, 3, 4, 5]
name = ['a', 'b', 'c', 'd']


new_num = zip(num, name)

for i in new_num:
    print(i)
# (1, 'a')
# (2, 'b')
# (3, 'c')
# (4, 'd')

也可以经过强转再打印

num = [1, 2, 3, 4, 5]
name = ['a', 'b', 'c', 'd']


new_num = zip(num, name) 
print(list(new_num))
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

filter()

用于过滤可迭代对象中的元素,并根据给定的函数判断是否保留该元素

filter() 函数的语法如下:

filter(function, iterable)
  • function:用于判断每个元素是否保留的函数,它接受一个参数并返回布尔值(True 或 False),注意function不能加括号
  • iterable:要过滤的可迭代对象,如列表、元组等。
def is_str(num):
    return isinstance(num, str)


num_list = ['a', 1, 'b', '2', 3]
new_list = filter(is_str, num_list)
print(list(new_list))  # ['a', 'b', '2']

你可能感兴趣的:(Study,python,开发语言)