Python 常用内置函数

1. 类型构造与转换

bool

  • 判断真值 / 假值
python 复制代码
print(bool('Bob')) # True
print(bool('')) # False

print(bool(100)) # True
print(bool(0)) # False

print(bool([1, 2, 3])) # True
print(bool([])) # False

int

  • 生成整数(注意:使用无参构造函数时,它都会创建该类型的默认值)
  • 浮点数转为整数:向下取整
python 复制代码
empty_int = int()
print(empty_int) # 0

print(int(1.9)) # 1
print(int(1.4)) # 1
print(int('4')) # 4

float

  • 浮点数构造函数
python 复制代码
empty_float = float()
print(empty_float) # 0.0

print(float(True)) # 1.0

complex

  • 复数构造函数
python 复制代码
print(complex()) # 0j
print(complex(5)) # (5+0j)
print(complex(6, 1)) # (6+1j)
print(complex('7+2j')) # (7+2j), 字符串中不能有空格

str

  • 字符串构造函数
python 复制代码
empty_str = str()
print(repr(empty_str)) # ''

tuple

  • 元组构造函数
python 复制代码
empty_tuple = tuple()
print(empty_tuple) # ()

# 字符串转列表
coordinates = [1.5, 5.0]
print(tuple(coordinates)) # (1.5, 5.0)

list

  • 列表构造函数
python 复制代码
empty_list = list()
print(empty_list) # []

# 字符串转列表
characters = 'abc'
print(list(characters)) # ['a', 'b', 'c']

# 元组转列表
my_tuple = (1, 5)
print(list(my_tuple)) # []

set

  • 集合构造函数,自动消除重复元素
python 复制代码
list_with_dupl = [1, 1, 1, 2, 2, 3, 3, 3]

print(set(list_with_dupl)) # {1, 2, 3}
print(list(set(list_with_dupl))) # [1, 2, 3]

frozenset

  • 冻结集合构造函数(不可变对象,好处是可哈希)
python 复制代码
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})

dict

  • 字典构造函数
python 复制代码
empty_dict = dict()
print(empty_dict) # {}

empty_dict = {}
print(empty_dict) # {}

print(dict(a=1, b=2)) # {'a': 1, 'b': 2}

type

  • 返回类型
python 复制代码
nums = [1, 2, 3]
print(type(nums)) # <class 'list'>

2. 数值运算

abs

  • 返回绝对值
python 复制代码
n1 = 1.25
n2 = -10
n3 = 3 + 4j

print(abs(n1)) # 1.25
print(abs(n2)) # 10
print(abs(n3)) # 5

divmod

  • 执行带余数的除法运算
python 复制代码
print(divmod(7, 4)) # (1, 3)
print(divmod(3.5, 1.5)) # (2.0, 0.5)

pow

  • 指数运算,还可以取模
python 复制代码
print(pow(2, 3)) # 8
print(pow(2, 5, mod=3)) # 2

round

  • 四舍五入
python 复制代码
n = 12549.1234567

print(round(n, 5))  # 12549.12346
print(round(n, 3))  # 12549.123
print(round(n, 0))  # 12549.0
print(round(n))     # 12549
print(round(n, -1)) # 12550

sum

  • 计算一个可迭代对象的和
python 复制代码
scores = [1, 2, 3, 4]

print(sum(scores)) # 10
print(sum(scores), start=100) # 110

max

  • 返回最大值,还可以用 key 指定方法(方法可以是 lambda,只要返回值为整数)
python 复制代码
scores = [20, 100, 40, 55]
print(max(scores)) # 100

names = ['Bob', 'James', 'Stephan']
print(max(names, key=len)) # Stephan

min

  • 返回最小值
python 复制代码
scores = [20, 100, 40, 55]
print(min(scores)) # 20

hash

  • 返回对象的哈希值(整数形式),对象必须是不可变的
python 复制代码
print(hash(frozenset([1, 2, 3])))
print(hash('Browns'))
print(hash((1, 2, 3)))

3. 序列与迭代

len

  • 获取可迭代对象的长度
python 复制代码
text = 'My name is Bob.'
print(len(text)) # 15

items = ['Cup', 'Apple', 'Plant']
print(len(items)) # 3

range

  • 生成整数序列(左闭右开),返回的是迭代器
python 复制代码
normal = range(5, 10)
print(list(normal)) # [5, 6, 7, 8, 9]

# 设定步长
normal = range(5, 10, 2)
print(list(normal)) # [5, 7, 9]

# 倒序输出, 步长为 -1
normal = range(10, 5, -1)
print(list(normal)) # [10, 9, 8, 7, 6]

slice

  • 切片
python 复制代码
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]

step_two = slice(0, 5) # [0:5]
print(nums(step_two)) # [1, 2, 3, 4, 5]

step_two = slice(None, None, 2) # [::2]
print(nums(step_two)) # [1, 3, 5, 7, 9]

# 反转
rev = slice(None, None, -1) # [::-1]
print(nums(step_two)) # [9, 8, 7, 6, 5, 4, 3, 2, 1]

iter

  • 将一个可迭起对象转化为迭代器(注意:1. 迭代器是会被耗尽的 2. 返回的是迭代器)
python 复制代码
from typing import Iterator

queue = [1, 2, 3]
my_iterator = iter(queue)

# 第一种用法
print(next(my_iterator)) # 1
print(next(my_iterator)) # 2
print(next(my_iterator)) # 3

# 第二种用法
print(list(my_iterator)) # [1, 2, 3]
print(list(my_iterator)) # [], 耗尽了(已经取出了所有元素)

next

  • 用于迭代器和生成器中,获取下一个值
python 复制代码
from typing import Iterator

my_iterator = iter(range(3)) # 相当于 [0, 1, 2]
print(next(my_iterator)) # 0
print(next(my_iterator)) # [1, 2]

enumerate

  • 获取可迭代对象中元素的索引和值
python 复制代码
abba = ['a', 'b', 'c', 'd']

# 方法1
enumeration = enumerate(abba)
print(list(enumeration)) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

# 方法2
for i, member in enumerate(abba, start=1):
    print(i, member, sep=': ') 

"""
1: a
2: b
3: c
4: d
"""

filter

  • 过滤可迭代对象中符合条件的元素
python 复制代码
names = ['James', 'John', 'Jam', 'Bob']

j_names = filter(lambda s: s[0].lower() == 'j', names)
print(j_names) # ['James', 'John', 'Jam']

map

  • 对可迭代对象中的每个元素应用指定的函数,返回一个迭代器
python 复制代码
from typing import Iterator

def square(n):
    return n * n

# 传入定义函数
squared = map(square, [1, 2, 3])
print(list(squared)) # [2, 4, 9]

# 传入 lambda 函数
all_upper = map(lambda s: s.upper(), ['Bob', 'Mike'])
print(list(all_upper)) # ['BOB', 'MIKE']

zip

  • 将多个可迭代对象中的对应元素打包成元组,这些元组会组成一个列表(压缩到最短长度)
python 复制代码
a = ['a', 'b', 'c']
b = [1, 2, 3, 4]
c = [True, False, True]

zipped = zip(a, b, c)
print(list(zipped)) [('a', 1, True), ('b', 2, False), ('c', 3, True)]

reversed

  • 返回一个反向迭代器
python 复制代码
sequence = [1, 2, 3, 4, 5]
r = reversed(sequence)
print(list(r)) # [5, 4, 3, 2, 1]

sorted

  • 排序,key 选择方式,reverse 选择反转
python 复制代码
mixed = [1, 5, 3, 2, 4]
print(sorted(mixed)) # [1, 2, 3, 4, 5]

names = ['Bob', 'Amanda', 'John', 'Charles']
print(sorted(names, key=len, reverse=True)) # 字符串默认 ASCII 排序

all

  • 与运算
python 复制代码
v1 = [1, 1, 1] # True
v2 = [1, 0, 1] # False

any

  • 或运算
python 复制代码
v1 = [1, 1, 1] # True
v2 = [1, 0, 1] # True
v3 = [0, 0, 0] # False

4. 字符串与编码

chr

  • 将整数转化为对应的 Unicode 字符
python 复制代码
print(chr(65)) # A
print(chr(67)) # C
print(chr(69)) # E

ord

  • 获取字符的 Unicode 编码(ordinal)
python 复制代码
print(ord('A')) # 65

ascii

  • 返回对象的 ASCII 形式
python 复制代码
# 处理普通字符串
print(ascii('runoob')) # 'runoob'

# 处理包含非 ASCII 字符的字符串
print(ascii('盖若')) # '\u76d6\u82e5'

bin

  • 把数字转化为二进制表示
python 复制代码
print(bin(10)) # 0b1010

repr

  • 返回该对象的表示形式(representation)
python 复制代码
print(repr(10)) # 10
print(repr('Bob')) # 'Bob', 带上了引号

5. 对象属性与反射

dir

  • 查找对象的所有属性和方法
python 复制代码
print(dir(int))
print(dir('hello')) # 等价于 dir(str)

id

  • 返回任意对象的唯一标识符
python 复制代码
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l3 = l1

print(l1 == l2) # True
print(l1 is l2) # False, id(l1) != id(l2)
print(l3 is l1) # True

isinstance

  • 检查某个类型是否是另一个类型的实例
python 复制代码
print(isinstance('3', int)) # True
print(isinstance('text', str | int)) # False

issubclass

  • 判断一个类是否派生自另一个类,或者判断是否为同一个类
python 复制代码
class Parent:
    ...

class Child(Parent):
    ...

print(issubclass(Child, Parent)) # True
print(issubclass(Parent, Child)) # False

hasattr

  • 判断一个对象是否具有指定的属性
python 复制代码
class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate()
print(hasattr(point1, 'x')) # True
print(hasattr(point1, 'no')) # False

callable

  • 判断是否可调用
python 复制代码
my_obj = 'Bob'

def greet(name):
    print(f'Hello, {name}!')

print(callable(my_obj)) # False
print(callable(greet)) # True

6. 作用域与命名空间

globals

  • 返回当前作用域的全局变量
python 复制代码
print(globals())

locals

  • 返回当前作用域的局部变量
python 复制代码
print(locals())

7. 输入输出

print

  • 输出,还可以指定分隔符,结束符(在解包元素时很实用)
python 复制代码
print('Hello, world!')
print(1, 2, 3, sep=', ') # 1, 2, 3

peple = ['Bob', 'James', 'Sandra']
print(*people, sep=', ', end='.\n') # Bob, James, Sandra.

open

  • 打开文件和处理数据流
python 复制代码
file = 'secret.txt'

with open(file, 'r') as f:
    print(f.read())

8. 代码执行

eval

  • 执行一个字符串表达式,并返回表达式的值
python 复制代码
text = '10 + 30 * 2'
print(eval(text)) # 70

exec

  • 执行存储在字符串或文件中的 Python 代码,不返回任何值
python 复制代码
source = """
a = 10
b = 20

print(a + b)

for i in range(3):
    print('exec() for loop:', i)
"""

exec(source)

9. 帮助

help

  • 返回函数的说明文档,也可以是自定义函数(三引号间的内容)
python 复制代码
help(print)
相关推荐
Piar1231sdafa2 小时前
蓝莓果实检测与识别——基于decoupled-solo_r50_fpn_1x_coco模型实现
python
行走的bug...2 小时前
python项目管理
开发语言·python
其美杰布-富贵-李2 小时前
tsai 完整训练流程实践指南
python·深度学习·时序学习·fastai
m0_462605222 小时前
第N9周:seq2seq翻译实战-Pytorch复现-小白版
人工智能·pytorch·python
纪伊路上盛名在2 小时前
记1次BioPython Entrez模块Elink的debug
前端·数据库·python·debug·工具开发
CryptoRzz2 小时前
日本股票 API 对接实战指南(实时行情与 IPO 专题)
java·开发语言·python·区块链·maven
ss2732 小时前
考研加油上岸祝福弹窗程序
python
乾元2 小时前
基于时序数据的异常预测——短期容量与拥塞的提前感知
运维·开发语言·网络·人工智能·python·自动化·运维开发
江上清风山间明月2 小时前
使用python将markdown文件生成pdf文件
开发语言·python·pdf