stakusir

前言

承接上文,复习完字符串,根据考纲,基本数据类型中还有数字尚未复习,那么今天火速复习一下!

数字

众所周知,数字分为整型(int)、浮点型(float)、复数(complex),数字的运算除了加减乘除之外,还有取余、取整等运算。

本次复习我们跳过以上,重点复习一下有关数字的函数。

数字类型转换

int(x [,base ])         x转换为一个整数  
long(x [,base ])        x转换为一个长整数  
float(x )               x转换到一个浮点数  
complex(real [,imag ])  创建一个复数  
str(x )                 将对象 x 转换为字符串  
repr(x )                将对象 x 转换为表达式字符串  
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象  
tuple(s )               将序列 s 转换为一个元组  
list(s )                将序列 s 转换为一个列表  
chr(x )                 将一个整数转换为一个字符  
unichr(x )              将一个整数转换为Unicode字符  
ord(x )                 将一个字符转换为它的整数值  
hex(x )                 将一个整数转换为一个十六进制字符串  
oct(x )                 将一个整数转换为一个八进制字符串
......

数字函数

abs(x)                  返回x的绝对值  
ceil(x)                 返回x的上入整数  
exp(x)                  返回e的x次幂  
floor(x)                返回x的下舍整数  
max(x1,x2,...)          返回最大值  
min(x1,x2,...)          返回最小值  
pow(x,y)                x的y次方,相当于x**y  
......

随机数函数

有关随机数的函数,基本上要用到random库,而random库也是计算机二级必考点。

dir(random)

[\'BPF\', \'LOG4\', \'NV_MAGICCONST\', \'RECIP_BPF\', \'Random\', \'SG_MAGICCONST\', \'SystemRandom\', \'TWOPI\', 
\'_Sequence\', \'_Set\', \'__all__\', \'__builtins__\', \'__cached__\', \'__doc__\', \'__file__\', \'__loader__\',
\'__name__\', \'__package__\', \'__spec__\', \'_accumulate\', \'_acos\', \'_bisect\', \'_ceil\', \'_cos\', \'_e\',
\'_exp\', \'_inst\', \'_log\', \'_os\', \'_pi\', \'_random\', \'_repeat\', \'_sha512\', \'_sin\', \'_sqrt\', \'_test\',
\'_test_generator\', \'_urandom\', \'_warn\', \'betavariate\', \'choice\', \'choices\', \'expovariate\', \'gammavariate\',
\'gauss\', \'getrandbits\', \'getstate\', \'lognormvariate\', \'normalvariate\', \'paretovariate\', \'randint\', \'random\',
\'randrange\', \'sample\', \'seed\', \'setstate\', \'shuffle\', \'triangular\', \'uniform\', \'vonmisesvariate\', \'weibullvariate\']

主要讲一讲常用的choice(),choices(),randint(),random(),randrange(),shuffle(),uniform()

import random
random.choice([1,2,3,4,5])          #从序列中随机抽取一个元素
random.choices([1,2,3,4,5], k=5)    #从序列中随机选取k次元素,组成列表,可分配权重
random.randint(0,9)                 #从范围内随机选一个整数
random.random()                     #从0,1间随机选一个浮点数,不接受参数
random.randrange(0,100,2)           #从范围内按指定数字递增的顺序随机一个数
random.shuffle(list)                #将序列随机排序
random.uniform(0,9)                #从范围内随机选一个浮点数

(详情参见https://www.runoob.com/python/python-numbers.html)

分类:

技术点:

相关文章:

  • 2021-11-16
  • 2021-05-07
  • 2021-11-11
  • 2022-01-11
  • 2021-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-04-03
猜你喜欢
  • 2022-12-23
  • 2021-04-05
  • 2022-01-01
  • 2022-12-23
  • 2022-01-03
  • 2021-11-25
  • 2022-01-13
相关资源
相似解决方案