python内置函数、数学模块、随机模块(二)

简介: python内置函数、数学模块、随机模块(二)

python内置函数、数学模块、随机模块(一):https://developer.aliyun.com/article/1495754

2、数学模块

import math
 

1 ceil() 向上取整操作

(对比内置round) ***  不管小数是多少,直接向上进位
res = math.ceil(3.01)
res = math.ceil(-3.45)
print(res)

2 floor() 向下取整操作

(对比内置round) ***
res = math.floor(3.99)
res = math.floor(-3.99)
print(res)

3 pow() 计算一个数值的N次方(结果为浮点数) (对比内置pow)

"""结果为浮点数,必须是两个参数"""
res = math.pow(2,3)
#res = math.pow(2,3,3) error
print(res)

4 sqrt() 开平方运算(结果浮点数)

res = math.sqrt(9)
print(res)

5 fabs() 计算一个数值的绝对值

(结果浮点数) (对比内置abs)
res = math.fabs(-1)
print(res)

6 modf() 将一个数值拆分为整数和小数两部分组成元组

res = math.modf(3.897)
print(res)

7 copysign() 将参数第二个数值的正负号拷贝给第一个 (返回一个小数)

不用管第一个数的符号正负,直接将第二个数的符号赋给第一个数

res = math.copysign(-12,-9.1)
print(res)

8 fsum() 将一个容器数据中的数据进行求和运算 (结果浮点数)(对比内置sum)

lst = [1,2,3,4]
res = math.fsum(lst)
print(res)

9 圆周率常数 pi ***

计算圆得面积,周长等需要调用π,这个常量。只能通过math.pi来调出

print(math.pi)

3、 随机模块

import random

1 random()

获取随机0-1之间的小数(左闭右开) 0<=x<1

res = random.random()
print(res)

2 randrange() 随机获取指定范围内的整数(包含开始值,不包含结束值,间隔值) ***

#一个参数
res = random.randrange(3)
print(res) # 0 1 2

#二个参数
res = random.randrange(3,6) # 3 4 5
print(res)

#三个参数
res = random.randrange(1,9,4) # 1 5 
print(res)

res = random.randrange(7,3,-1) # 7 6 5 4
print(res)


3 randint() 随机产生指定范围内的随机整数 (了解) 头尾全包括

res = random.randint(1,3) # 1 2 3
#res = random.randint(3,5,1)  error   只能包含两个参数
print(res)

4 uniform()

获取指定范围内的随机小数(左闭右开)  网络里面用的较多 ***
res = random.uniform(0,2) # 0<= x < 2
print(res)
res = random.uniform(2,0)
print(res)

原码解析:

a = 2 , b = 0
return 2 + (0-2) * (0<=x<1)
x = 0 return 2 取到
x = 1 return 0 取不到
0 < x <= 2
return a + (b-a) * self.random()

5 choice()

随机获取序列中的值(多选一) 可用于字符串,列表,元祖**

lst = ["孙凯喜","王永飞","于朝志","须臾间","含税小"]
res = random.choice(lst)
print(res)

def mychoice(lst):
    index_num = random.randrange(len(lst))
    return lst[index_num]
print(mychoice(lst))

从字符串中随机选一个

6 lambda 改造

mychoice = lambda lst : lst[   random.randrange(len(lst))     ]
print(mychoice(lst))

7 sample()

随机获取序列中的值(多选多) [返回列表] **

tup = ("孙凯喜","王永飞","于朝志","须臾间","含税小")
res = random.sample(tup,3)   #可以控制随机选的个数
print(res)

8 shuffle() 随机打乱序列中的值(直接打乱原序列) 返回列表**

lst = ["孙凯喜","王永飞","于朝志","须臾间","含税小"]
random.shuffle(lst)    
print(lst)

只支持列表被打乱


相关文章
|
1天前
|
Python
Python中的模块与包——深入理解与应用
Python中的模块与包——深入理解与应用
|
2天前
|
存储 Python
Python中的函数与模块:核心概念与实践
Python中的函数与模块:核心概念与实践
|
2天前
|
Python
蓝易云 - python之函数返回数据框
这是一个简单的例子,实际上,你可以根据需要,创建更复杂的数据框,包括多个列,不同类型的数据,等等。
9 0
|
4天前
|
Python
|
5天前
|
Python
python(pip)包/模块:如何离线安装?
python(pip)包/模块:如何离线安装?
9 0
|
5天前
|
Python
Python 模块
Python 模块
6 0
|
5天前
|
Serverless 数据处理 开发者
Python基础教程——模块
Python基础教程——模块
|
5天前
|
算法 数据可视化 数据处理
Python基础教程——函数
Python基础教程——函数
|
5天前
|
Python
Python基础 笔记(十) 文件操作、异常、模块
Python基础 笔记(十) 文件操作、异常、模块
18 3
Python 函数合集:足足 68 个内置函数,请收好(五)
内置函数就是python给你提供的, 拿来直接用的函数,比如print.,input等。截止到python版本3.6.2 python一共提供了68个内置函数。
Python 函数合集:足足 68 个内置函数,请收好(五)