python3 内置函数

内置函数导图:
https://www.processon.com/view/link/5b4ee15be4b0edb750de96ac#map

'''python中的内置函数分类
1、输入输出:print、input
需要注意的是input输入的数据是字符串类型。
'''

print("Hello world")


age = input("请输入您的年龄:").strip()
print(age)
print(type(age))
Hello world
请输入您的年龄:18
18
<class 'str'>

'''2、数据类型强制转换:int、bool、str、list、dict、tuple、set、float、bytes'''
bs = bytes("中国", encoding="utf-8")
print(bs)
print(type(bs))

bs2 = "中国".encode("utf-8")
print(bs2)
print(type(bs2))
b'xe4xb8xadxe5x9bxbd'
<class 'bytes'>
b'xe4xb8xadxe5x9bxbd'
<class 'bytes'>

'''3、进制转换:bin、oct、int、hex、format'''
# 十进制转换为二进制bin和format
print(bin(188))
print(type(bin(188)))

print(format(188, "b"))
0b10111100
<class 'str'>
10111100

# 十进制转换为八进制oct和format
print(oct(188))
print(type(oct(188)))

print(format(188, "o"))
0o274
<class 'str'>
274

# 十进制转换为十六进制hex和format
print(hex(188))
print(type(hex(188)))

print(format(188, "x"))  # 小写

print(format(188, "X"))  # 大写
0xbc
<class 'str'>
bc
BC

# 二进制转换为十进制int
print(int("10111100", base=2))

print(int("0b10111100", base=2))
188
188

# 八进制转换为十进制int
print(int("0o274", base=8))

print(int("274", base=8))
188
188

# 十六进制转换为十进制
print(int("0xbc", base=16))

print(int("bc", base=16))
188
188

'''4、编码相关:chr、ord'''
# 取字符串在ascii或unicode中的数值
o = ord("a")
print(o)

o2 = ord("")
print(o2)

# 取数值在ascii或unicode中的字符串
s2 = chr(97)
print(20013)
print(s2)
97
20013
20013
a

'''5、数学相关:max、min、sum、divmod、abs、pow、round'''
# max取最大值
print(max([4, 6, 7, 1, 0]))
7

# min取最小值
print(min([4, 6, 7, 1, 0]))
0

# sum求和
print(sum([4, 6, 7, 1, 0]))
18

# divmod求商和余数
print(divmod(10, 3))
(3, 1)

'''请通过分页对数据进行展示
要求:每页显示10条数据,让用户输入要查看的页码数
'''
lst = []

for i in range(88):
    dic = {"name": f"张{i}", "email": f"aa{i}@163.com"}
    lst.append(dic)
    
total_num = len(lst)  # 总数据条数
per_page_num = 10  # 每页显示的数据条数
max_page, last_page = divmod(total_num, per_page_num)  

if last_page:
    max_page += 1  # 一共有max_page页
    
choice = int(input(f"共{total_num}条数据,共{max_page}页。请输入你要查看的页码数:").strip())

start = (choice-1) * per_page_num  # 开始切片位置
end = choice*per_page_num  # 结束切片位置

if choice in range(1, max_page+1):
    for item in lst[start:end]:
        print(item)
else:
    print(f"输出错误,请输入1-{max_page}")
共88条数据,共9页。请输入你要查看的页码数:8
{'name': '张70', 'email': 'aa70@163.com'}
{'name': '张71', 'email': 'aa71@163.com'}
{'name': '张72', 'email': 'aa72@163.com'}
{'name': '张73', 'email': 'aa73@163.com'}
{'name': '张74', 'email': 'aa74@163.com'}
{'name': '张75', 'email': 'aa75@163.com'}
{'name': '张76', 'email': 'aa76@163.com'}
{'name': '张77', 'email': 'aa77@163.com'}
{'name': '张78', 'email': 'aa78@163.com'}
{'name': '张79', 'email': 'aa79@163.com'}



# abs求绝对值
print(abs(-8))

8


# pow求次幂
print(pow(2, 3))

print(2**3)

8
8


# round四舍五入
print(round(3.1415926, 2))

print(round(3.1415926, 4))

3.14
3.1416

'''6、迭代器、生成器相关:iter、next、range'''

# range(n) 表示0到n的可迭代数据集
r = range(10)
print(r)
print(type(r))

# range(start, end) [start, end) 顾头不顾尾 
r2 = range(1, 10)
print(r2)
print(type(r2))

# range(start, end, step) 步长为step, 当step为正数时,表示从start到end-1,每step个取一个
r3 = range(1, 10, 2)
print(list(r3))

# range(start, end, step) 当step为负数时,表示从start到end-1,每abs(step)个取一个
r4 = range(10, 2, -2)
print(list(r4))
range(0, 10)
<class 'range'>
range(1, 10)
<class 'range'>
[1, 3, 5, 7, 9]
[10, 8, 6, 4]

'''可迭代对象使用iter可以生成一个迭代器,iter和__iter__等同'''
lst = [3, 5, 1]

# 生成一个迭代器
it = iter(lst)
print(it)

# 从迭代器中取值
v1 = next(it)
print(v1)
v2 = next(it)
print(v2)
v3 = next(it)
print(v3)

# 当数据取完时,再使用next会报错StopIteration
v4 = next(it)
print(v4)
<list_iterator object at 0x0000000005A83B70>
3
5
1
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-46-76deef2c56d9> in <module>()
     15 
     16 # 当数据取完时,再使用next会报错StopIteration
---> 17 v4 = next(it)
     18 print(v4)

StopIteration: 


'''7、内存相关:id、hash'''

# 不可变的数据类型,就是可哈希的数据类型:int、bool、str、tuple
# 取变量的哈希值
h = hash("中国")
print(h)

# 获取内存地址
i = id("中国")
print(i)

i2 = id({"name":"lily", "age": 18})
print(i2)
-4883128536252665742
95047904
95109912

'''可变的数据类型,没有hash值'''
h = hash({"name":"lily", "age": 18})
print(h)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-b45da8ba84b8> in <module>()
      1 '''可变的数据类型,没有hash值'''
----> 2 h = hash({"name":"lily", "age": 18})
      3 print(h)

TypeError: unhashable type: 'dict'


'''8、字符串类型代码的执行:exec、eval、compile'''
# exec无返回值
print(exec("[3, 5, 1]"))
exec("print(1)")

# eval有返回值
print(eval("[3, 5, 1]"))
eval("print(2)")

# compile
exec(compile("for i in range(8, 10):print(i)", "", "exec"))
None
1
[3, 5, 1]
2
8
9

'''9、文件操作相关:open'''
with open("a.txt", "w", encoding="utf-8") as f:
    f.write("我正在写入文件内容")
'''10、相关的内置函数:sorted、filter、map、reduce、zip、all、any、enumerate'''
# sorted(iter, key=func, reverse=False/True)
# iter:可迭代对象,可迭代对象中的每个元素作为func的参数进行传递
# key: 函数名,根据函数体的返回值,进行排序,将原可迭代对象,重新排序,并返回
# reverse:倒序
# sorted 对可迭代对象根据条件进行排序,没有条件,默认升序排序
s = sorted([5, 1, 6])
print(s)

# sorted 对可迭代对象根据条件进行排序,升序
s2 = sorted(["abc", "4", "sd"], key=lambda x: len(x))
print(s2)

# sorted 对可迭代对象根据条件进行排序,降序
s3 = sorted(["abc", "4", "sd"], key=lambda x: len(x), reverse=True)
print(s3)
[1, 5, 6]
['4', 'sd', 'abc']
['abc', 'sd', '4']

# filter 筛选,过滤用的,返回的是一个迭代器
f = filter(lambda x: x > 20, [21, 17, 24])
print('__iter__' in dir(f))
print(list(f))
True
[21, 24]

# map 映射,对可迭代对象中的每个元素做相同的操作,返回的是一个迭代器
m = map(lambda x: x+"_good", ["lily", "lucy", "tom"])
print("__iter__" in dir(m))
print(list(m))
True
['lily_good', 'lucy_good', 'tom_good']

# reduce 对可迭代对象中的每个元素做指定的操作,函数默认有两个参数,返回一个结果数据
from functools import reduce

# 注意观察,对长度为3的可迭代对象做reduce操作,其实一共执行了3-1次函数的调用
def func(x, y):
    print(1)
    return x + y

r = reduce(func, [1, 2, 3])
print(r)

# 使用匿名函数
r2 = reduce(lambda x, y: x+y, [1, 2, 3])
print(r2)
1
1
6
6

# zip拉链函数,水桶效应, 返回一个迭代器
lst = [0, 1, 2]
lst2 = ["a", "b", "c"]
z = zip(lst, lst2)
print(z)
print("__next__" in dir(z))
print(list(z))
# 取完了,就为空
print(list(z))

# 也可以返回一个字典
z = zip(lst, lst2)
print(z)
print(dict(z))
# 取完了,就为空
print(dict(z))
<zip object at 0x0000000005CE8A08>
True
[(0, 'a'), (1, 'b'), (2, 'c')]
[]
<zip object at 0x0000000005CDDE08>
{0: 'a', 1: 'b', 2: 'c'}
{}

# all相当于and,最后返回的是bool值
re = all([3, 4, "a"])
print(re)

re1 = 3 and 4 and "a"
print(re1)
True
a

# any相当于or,最后返回的是bool值
re = any([3, 4, "a"])
print(re)

re1 = 3 or 4 or "a"
print(re1)
True
3

# enumerate枚举, enumerate(可迭代对象),从0开始计数
for i, v in enumerate(["one", "two", "three"]):
    print(i, v)
    
# enumerate(可迭代对象, n) ,从n开始计数
for i, v in enumerate(["one", "two", "three"], 6):
    print(i, v)
0 one
1 two
2 three
6 one
7 two
8 three

'''11、字符串格式化format'''
# 居中,空白补空
print(format("居中", "^20"))

# 居中,*号补空
print(format("居中", "*^20"))

# 居左,空白补空
print(format("居左", "<20"))

# 居左,=号补空
print(format("居左", "=<20"))

# 居右,空白补空
print(format("居右", ">20"))

# 居右,#号补空
print(format("居右", "#>20"))

# 保留2位小数
print(format(3.1415926, ".2f"))

# 保留4位小数,会四舍五入哦
print(format(3.1415926, ".4f"))
         居中         
*********居中*********
居左                  
居左==================
                  居右
##################居右
3.14
3.1416

'''12、调用相关:callable'''
# 可调用的,返回bool值
def func():
    print("func")
callable(func)
True

'''13、查看内置属性'''
print(dir(list))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']



原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10782563.html