Python基础【第四篇】:基础数据类型(数字型)

基本数据类型

标准数据类型

  • Number(数值)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Set(集合)
  • Dictionary(字典)

像大多数语言一样,数值类型的赋值和计算都是很直观的。

内置的 type() 函数可以用来查询变量所指的对象类型。

a = 1
b = 1.2
c = 2 + 3j
d = [1,2,3,4]
e = {1,2,3}
print("a的数据类型为:",type(a))
print("b的数据类型为:",type(b))
print("c的数据类型为:",type(c))
print("d的数据类型为:",type(d))
print("e的数据类型为:",type(e))

输出:

a的数据类型为: <class 'int'>
b的数据类型为: <class 'float'>
c的数据类型为: <class 'complex'>
d的数据类型为: <class 'list'>
e的数据类型为: <class 'set'>

此处还可以使用isinstance(value,class)来判断。

a = 1
print(isinstance(a,int))      #True
print(isinstance(a,float))    #False

注意:在 Python2 中是没有布尔型的,它用数字 0 表示 False,用 1 表示 True。到 Python3 中,把 True 和 False 定义成关键字了,但它们的值还是 1 和 0,它们可以和数字相加。

>>> a= 1
>>> b=True
>>> isinstance(a,int)
True
>>> isinstance(b,int)
True
>>> type(b)
<class 'bool'>
>>> type(a)
<class 'int'>
>>> isinstance(a,bool)
False

变量b是bool类型,但是isinstance(b,int)返回True,可见bool类型可以是与int类型相加。

但是a是int类型,但是isinstance(a,bool),返回False,可见int类型的数值1并不能看为Ture。

数据类型(Number)

Python 数字数据类型用于存储数值。

数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。

1 >>> a = 2
2 >>> id(a)
3 1826292208
4 >>> a = a + 3
5 >>> id(a)
6 1826292304
7 >>>

Python 支持三种不同的数值类型:

  • 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
  • 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示
  • 复数( (complex)) - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。

我们可以使用十六进制和八进制来代表整数

十六进制以0x开头,八进制以0o开头

1 >>> a = 0x1A
2 >>> a
3 26
4 >>> b = 0o77
5 >>> b
6 63
7 >>>

 python数字类型转换

python支持的数值类型有整形,浮点型,复数型。

  • int(x) 将x转换为一个整数。

  • float(x) 将x转换到一个浮点数。

  • complex(x) 将x转换到一个复数,实数部分为 x,虚数部分为 0,虚数单位是j不是i。

  • complex(x, y) 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。

1 >>> a = 2
2 >>> float(a)
3 2.0
4 >>> complex(a)
5 (2+0j)
6 >>> int(a)
7 2
8 >>>

注意:

  • 1、Python可以同时为多个变量赋值,如a, b = 1, 2。
  • 2、一个变量可以通过赋值指向不同类型的对象。
  • 3、数值的除法包含两个运算符:/返回一个浮点数,//返回一个整数。
  • 4、在混合计算时,Python会把整型转换成为浮点数。
  • 5、复数不可以转化为浮点数或者整数。

对于第二条,就是因为数值类型的变量再次赋值需要重新划分内存,不像Java和C,重新赋值需要类型转换。

>>> a = 1
>>> a = 1.2

对于第五条

1 >>> a = 2+2j
2 >>> float(a)
3 Traceback (most recent call last):
4   File "<stdin>", line 1, in <module>
5 TypeError: can't convert complex to float
6 >>> int(a)
7 Traceback (most recent call last):
8   File "<stdin>", line 1, in <module>
9 TypeError: can't convert complex to int

 但是complex(复数)其实是python中的一个类,它有属性和方法,其中两个属性real、imag就是复数的实部和虚部。

>>> a = 2 + 3j
>>> a.real
2.0
>>> a.imag
3.0

复数还有一个方法:conjugate()返回其共轭复数。

>>> a = 2 + 3j
>>> a.conjugate()
(2-3j)
>>>

 

int的“魔法”

因为int是一个整数类,有许多内置方法。

class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.
    
    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by '+' or '-' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    """
    def bit_length(self): 
        """ 返回表示该数字的时占用的最少位数 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回该复数的共轭复数 """
        """ Returns self, the complex conjugate of any int. """
        pass

    def __abs__(self):
        """ 返回绝对值 """
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y):
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): 
        """ 比较两个数大小 """
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y):
        """ 强制生成一个元组 """ 
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y): 
        """ 相除,得到商和余数组成的元组 """ 
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y): 
        """ x.__div__(y) <==> x/y """
        pass

    def __float__(self): 
        """ 转换为浮点类型 """ 
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y): 
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, name): 
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
        pass

    def __hash__(self): 
        """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
        """ x.__hash__() <==> hash(x) """
        pass

    def __hex__(self): 
        """ 返回当前数的 十六进制 表示 """ 
        """ x.__hex__() <==> hex(x) """
        pass

    def __index__(self): 
        """ 用于切片,数字无意义 """
        """ x[y:z] <==> x[y.__index__():z.__index__()] """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.
        
        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by '+' or '-' and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        # (copied from class doc)
        """
        pass

    def __int__(self): 
        """ 转换为整数 """ 
        """ x.__int__() <==> int(x) """
        pass

    def __invert__(self): 
        """ x.__invert__() <==> ~x """
        pass

    def __long__(self): 
        """ 转换为长整数 """ 
        """ x.__long__() <==> long(x) """
        pass

    def __lshift__(self, y): 
        """ x.__lshift__(y) <==> x<<y """
        pass

    def __mod__(self, y): 
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y): 
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self): 
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): 
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __nonzero__(self): 
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __oct__(self): 
        """ 返回改值的 八进制 表示 """ 
        """ x.__oct__() <==> oct(x) """
        pass

    def __or__(self, y): 
        """ x.__or__(y) <==> x|y """
        pass

    def __pos__(self): 
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None): 
        """ 幂,次方 """ 
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y): 
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y): 
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y): 
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y): 
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self): 
        """转化为解释器可读取的形式 """
        """ x.__repr__() <==> repr(x) """
        pass

    def __str__(self): 
        """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
        """ x.__str__() <==> str(x) """
        pass

    def __rfloordiv__(self, y): 
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rlshift__(self, y): 
        """ x.__rlshift__(y) <==> y<<x """
        pass

    def __rmod__(self, y): 
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y): 
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y): 
        """ x.__ror__(y) <==> y|x """
        pass

    def __rpow__(self, x, z=None): 
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rrshift__(self, y): 
        """ x.__rrshift__(y) <==> y>>x """
        pass

    def __rshift__(self, y): 
        """ x.__rshift__(y) <==> x>>y """
        pass

    def __rsub__(self, y): 
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y): 
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y): 
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sub__(self, y): 
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y): 
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs): 
        """ 返回数值被截取为整形的值,在整形中无意义 """
        pass

    def __xor__(self, y): 
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虚数,无意义 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 数字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 实属,无意义 """
    """the real part of a complex number"""

int
int的方法
  • abs(a) : 求取绝对值。abs(-1)
  • bit_length :  当前数字的二进制,至少用n位表示,a.bit_length
  • any(list or tuple):如果列表或者元祖中有非零的数,则返回True,否则返回False
  • all(list or tuple):如果列表或者元祖中全部是非零的数,则返回True,否则返回False
  • max(list) : 求取list最大值。max([1,2,3])
  • min(list) : 求取list最小值。min([1,2,3])
  • sum(list) : 求取list元素的和。 sum([1,2,3]) >>> 6
  • sorted(list) : 排序,返回排序后的list。
  • len(list) : list长度,len([1,2,3])
  • divmod(a,b): 获取商和余数。 divmod(5,2) >>> (2,1)
  • pow(a,b) : 获取乘方数。pow(2,3) >>> 8
  • round(a,b) : 获取指定位数的小数。a代表浮点数,b代表要保留的位数。round(3.1415926,2) >>> 3.14
    • round(x):返回x四舍五入的数
      • 如果整数部位是奇数,且小数部位为0.5,则加一,>>>round(1.5) >>>2
      • 如果整数部分是偶数,且小数部位为0.5,则不加一,>>>round(2.5) >>>2
  • range(a,b) : 生成一个a到b的整数数组,左闭右开。 range(1,10) >>> [1,2,3,4,5,6,7,8,9]
  • int(str) : 转换为int型。int('1') >>> 1
  • float(int/str) : 将int型或字符型转换为浮点型。float('1') >>> 1.0
  • ascii(obj) : 类似repr(),返回一个输入对象的可打印字符串,但是在返回字符串中去掉非ASCII编码字符。类似python2中的repr()。

 

 

 


 

 python中的数学函数

 

数学函数在math模块中,必须import math

函数返回值 ( 描述 )
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5

cmp(x, y)

如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃 。使用 使用 (x>y)-(x<y) 替换。
exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
<round(x ,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x) 返回数字x的平方根。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python已经不能使用cmp()函数了,使用下面的下列五个函数代替。

 1 >>> import operator         #导入operator模块
 2 >>> operator.gt(1,2)         #  >
 3 False
 4 >>> operator.lt(1,2)         #  <
 5 True
 6 >>> operator.eq(1,2)         #  =
 7 False
 8 >>> operator.le(1,2)         #  <=
 9 True
10 >>> operator.ge(1,2)         #  >=
11 False    

 

 Python中的随机函数

 随机函数都在Python自带的模块random中,必须执行import random,才能使用随机函数。

  • choice(seq)    从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
  • randrange(start,end,deta)    从区间[start,end)中以基数deta取随机数
    • random.randrange(100):表示从0~99取整数。
    • random.randrange(1,7,2):返回序列(1,3,5)中的数。
    • 基数默认为整数1,且start,end,deta必须是整数。
  • random()    从区间[0,1)选取随机数。
  • seed(x)    下文详解。
  • shuffle()    将序列的所有元素随机排序。list = [2,4,5,3] ,random.shuffle(list),则list将变为随机的序列。此方法无返回值,作用在原来的序列上。
  • uniform    随机生成下一个实数,它在[x,y]范围内。

 详解seed()方法

参考https://blog.csdn.net/qinglu000/article/details/46119621

 random生成随机数时,大家有没有想过这样的问题:生成随机数的机制是怎样的?是不是这些随机数只是一些乱序列表,早已经确定了,只需要一个开头,就会生成一个随机序列,那么开头是什么呢,开头就是此处的随机种子seed。

每一个seed对应一个所谓的随机序列, 通常情况下,你可以用 DateTime.Now.Millisecend() 也就是当前始终的毫秒来做Seed .因为毫秒对你来说是一个1000以内的随即数字。 这样可以大大改善保准库的Random结果的随机性。 不过这仍然算不上是完全随机,因为重复的概率还是千分之一。

那么到底有多少个seed呢,如果每个seed都不同,我每次生成随机数都改变一个seed,那么不就可以生成不同的随机序列了吗,这就可以达到了随机的效果了呀。很不理想的是:在调用了N次之后,输出结果就会循环为最开始的序列了,标准库random所能生成的不同结果的个数也是有限的。32位系统也就循环几万次就会开始重复。

 

先看一个效果:

1 import random          #导入random模块;
2 random.seed(10)         #改变随机种子为10;
3 print("种子为10的第一个随机数:",random.random())           #生成两个随机数
4 print("种子为10的第二个随机数:",random.random())
5 random.seed(10)         #更新
6 print("更新之后种子为10的第一个随机数:",random.random())   #生成两个随机数
7 print("更新之后种子为10的第二个随机数:",random.random())

输出结果:

种子为10的第一个随机数: 0.5714025946899135
种子为10的第二个随机数: 0.4288890546751146
更新之后种子为10的第一个随机数: 0.5714025946899135
更新之后种子为10的第二个随机数: 0.4288890546751146

可见改变种子之后,生成的序列是固定的,每一个种子对应一个序列。当我们产生随机数时,我们不必去设定这些种子,Python会自动设定,但是每次生成的随机种子都不一样。

1 import random          #导入random模块
2 random.seed()    #使用默认随机种子
3 print("默认种子的第一个随机数:",random.random())   #生成两个随机数
4 print("默认种子的第二个随机数:",random.random())
5 random.seed()    #更新
6 print("更新默认种子的第一个随机数:",random.random())   #生成两个随机数
7 print("更新默认种子的第二个随机数:",random.random())

输出:

1 默认种子的第一个随机数: 0.5404015988600108
2 默认种子的第二个随机数: 0.03439700573057336
3 更新默认种子的第一个随机数: 0.014591235334510344
4 更新默认种子的第二个随机数: 0.11515694193657355

可见就算更新默认的种子后,生成的随机序列也不一样,所以默认的种子也是随机的,每次产生的序列也是随机的。

shuffle()方法的拓展

实例

1 #!/usr/bin/python3
2 import random
3  
4 list = [20, 16, 10, 5];
5 random.shuffle(list)
6 print ("随机排序列表 : ",  list)
7  
8 random.shuffle(list)
9 print ("随机排序列表 : ",  list)

输出结果

随机排序列表 :  [16, 5, 20, 10]
随机排序列表 :  [10, 16, 20, 5]

 

 

 

 

-->

posted @ 2018-08-12 22:06  焕熊  阅读(517)  评论(0编辑  收藏  举报