Skip to content

内置函数

一些常用的内置函数

数据类型相关

python
int()  # 整数
float()  # 浮点数
str()  # 字符串
list()  # 列表
tuple()  # 元组
dict()  # 字典
set()  # 集合
bool()  # 布尔值

数学计算相关

python
abs(-1)  # 绝对值 1
max([1,2,3]) # 最大值 3
min([1,2,3]) # 最小值 1
sum([1,2,3])  # 求和 1+2+3=6
pow(2,3)  # 幂运算 2^3 = 8
round(2/3,2)  # 四舍五入 2/3=0.6666666666666666 四舍五入后为0.67

数据结构相关

python
format()  # 格式化字符串
ord()  # 字符转ASCII码
chr()  # ASCII码转字符


all([1,0,""])  # 全部为True才为True
any([1,0,""])  # 有一个为True就为True

lst = ["a", "b", "c"]
for index, item in enumerate(lst):
	print(index, item)

内存相关

python
id()  # 获取对象的内存地址
hash()  # 获取对象的哈希值

字符串相关

python
str1 = "hello world"
print(str1.upper())  # 大写 输出:HELLO WORLD
print(str1.lower())  # 小写 输出:hello world
print(str1.title())  # 标题 输出:Hello World

print(format("你好!{str1}")) # 格式化字符串 输出:你好!hello world

print(str1.replace("hello", "Hi")) # 替换字符串 输出:Hi world
print(str1.split(" ")) # 分割字符串 输出:['hello', 'world']
print(str1.find("world")) # 查找字符串 输出:5
print(str1.index("world")) # 索引字符串 输出:5
print(str1.count("l")) # 计数字符串 输出:3
print(str1.startswith("hello")) # 判断字符串开头 输出:True
print(str1.endswith("world")) # 判断字符串结尾 输出:True

print(str1.strip())   # 去除字符串首尾的空格 输出:hello world
print(str1.lstrip())  # 去除字符串左侧的空格 输出:hello world
print(str1.rstrip())  # 去除字符串右侧的空格 输出:hello world

print(str1.join(["hello", "world"])) # 字符串连接 输出:hello world

列表相关

python

lst = [1,3,1,4,5]
str1 = "hello world"
lst.extend([7,8]) # 合并列表
print(lst) # [1, 3, 1, 4, 5, 7, 8]

lst.remove(1) # 删除第一次出现的元素
print(lst) # [3, 1, 4, 5, 7, 8]

print(lst.pop(1)) # 删除指定元素并返回值 默认最后一个
print(lst) # [3, 1, 4, 5, 7]

lst.reverse() # 列表翻转
print(lst) # [7, 5, 4, 1, 3]

print(",".join(map(str,lst))) # 列表元素连接成字符串 输出:7,5,4,1,3

字典相关

python
dict1 = {"a": 1, "b": 2, "c": 3}

print(dict1.keys()) # 获取字典所有key 输出:dict_keys(['a', 'b', 'c'])
print(dict1.values()) # 获取字典所有value 输出:dict_values([1, 2, 3])
print(dict1.items()) # 获取字典所有key和value 输出:dict_items([('a', 1), ('b', 2), ('c', 3)])

print(dict1.get("a")) # 获取字典中key对应的value 输出:1

特殊函数

zip

  • 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
  • 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同
  • 利用 * 号操作符,可以将元组解压为列表。
python
import copy

li1 = ["a", "b", "c"]
li2 = ["c", "d", "e"]
# 加压
zip1 = zip(li1,li2)
# 必须先深度拷贝,否则下面的print()会改变zip1的数据结构,导致解压失败
zip2 = copy.deepcopy(zip1)
print(list(zip1))
# 解压
li3,li4 = zip(*zip2)

reduce

  • 函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
  • 通常用来对一个集合进行累计操作
python
from functools import reduce

li1 = [1,2,3,4,5]
# 遍历li1所有元素,将所有元素累计起来
print(reduce(lambda a,b: a+b, li1)) # 15

enumerate

  • enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
python
li1 = ["a", "b", "c"]
for index, item in enumerate(li1):
	print(index, item)