• Python学习week3-python数据结构介绍与列表


    1、python数据结构分类

    (1)常规分类:

      数值型:int、float、bool

      序列对象:list、str、tuple

      键值对:dict

    (2)根据可变与不可变分类:

    # 什么是可变?什么又是不可变?

    一般变量都会有三个属性:id,type,value;

    这里id与type不变,值改变则为可变数据类型;value改变,id就改变为不可变;

      不可变:数字,字符串,tuple

      可变:list,dict

    (3)按照访问顺序区分

      直接访问:数字

      顺序访问:字符串,列表,元组

      key值访问:字典

    2、python之数字处理

    2.1、round()函数

    # 四舍六入,五取最近偶数

    print(round(3.5)) # 4
    print(round(1.5)) # 2
    print(round(4.5)) # 4

    # 只有小数刚刚为:.5的时候是取最近偶数,如果超过5则为6入了,例如 round(2.51) 结果为3;

    2.2、math模块:floor()与ceil()

      floor() ==> 地板(向下取值)

      ceil()  ==>天花板(向上取值)

    import math
    
    print(math.floor(1.5)) # 向下取值为1
    print(math.ceil(1.5))  # 向上取值为2
    
    print(math.ceil(-1.5))  # 向上取值为-1
    print(math.floor(-1.5)) # 向下取值为-2

    2.3、int()与//

    # int取整,//整除并且向下取整

    1 print(10//3)         ==》3
    2 print(int(3.33))     ==》3

    2.4、min()、max()函数

    def max(*args, key=None): # known special case of max
        """
        max(iterable, *[, default=obj, key=func]) -> value
        max(arg1, arg2, *args, *[, key=func]) -> value
    ==================================================>
    # max(1,3,5) ==>5
    # max([1,3,4]) ==>4

    2.5、pow()与math.sqrt()

    1 # pow(x,y) ==>x**y
    2 pow(2,3)  ==>8
    3 
    4 # math.sqrt(x)  ==>return float  ===> x**0,5
    5 math.sqrt(100) ==> 10.0 

    2.6、进制转换函数

    1 print(bin(12)) # 10进制转二进制 0b1100
    2 print(oct(12)) # 10进制转八进制 0o14
    3 print(hex(12)) # 10进制转十六进制 0xc

    2.7、类型判断函数

    #  type(object) -> the object's type
    print(type(12)) ==》  <class 'int'>
    
    # isinstance(obj, class_or_tuple, /) A tuple, as in ``isinstance(x, (A, B, ...))``
    print(isinstance([123,23],(int,str))) # Fasle

    3、python之列表

    3.1、list列表的特点

    (1)列表在内存空间中表现是一段连续并且有序的地址空间,是一种线性的数据结构;

    (2)列表中的个体被称为元素,由若干个元素组成列表;

    (3)元素可以是任意对象(数字,字符串,列表,字典等)

    (4)列表中的元素根据索引号,顺序排列,可以通过索引号访问元素;

    (5)列表是可变的数据类型;

    3.2、列表,链表,queue,stack的差异

    # 列表和链表在内存中都是一种有序的线性的数据结构;

    # 不同的是列表是必须为连续的一段地址空间,通过索引的偏移量访问;而链表内存可以不连续,前一个空间只向后一个空间;

    (1)链表与列表的优缺点?

    # 列表由于必须是连续有序,所以列表的访问速度比较快,在不改变原来结构的情况下append数据也还可以,总结:列表访问快,修改慢

    # 链表的特点是上一个空间指向下一个空间,即如果要插入一个元素,只需要修改前后2个元素的空间指向即可,如果要访问,则需要遍历元素;总结:链表修改快,访问比较满;

    # 队列(queue)与栈(stack)

    队列特点:先进先出,类似于管道;list.pop(0)可以模拟

    栈特点:后进先出,类似于子弹夹;list.pop()可以模拟

    3.3、列表定义与初始化

    def __init__(self, seq=()): # known special case of list.__init__
         """
         list() -> new empty list
         list(iterable) -> new list initialized from iterable's items
         # (copied from class doc)
         """
    # list() 等于 l=[] 创建一个空列表
    # list(iterable) ==> iterable 为一个可迭代对象, list(range(5)) 等于 l=[0,1,2,3,4]

     3.4、列表索引访问

    # 索引,也称为下标

    # 正索引:从左至右,从0开始;负索引:从右到左,-1开始(最后一个元素);

    # 访问索引不能越界,不然会报错IndexError

     1 l=['a','b','c','d','e']
     2 
     3 '''
     4 # 格式:[start:end:step]
     5 [:]          提取开头(默认位置0)到结尾(默认位置-1)的整个字符串;
     6 [start:]         从start位置提取到结尾
     7 [:end]           从开头提取到end-1
     8 [start:end]      从start到end-1
     9 [start:end:step] 从start到end-1,每step个字符提取一个
    10 '''
    11 # [:]    提取开头(默认位置0)到结尾(默认位置-1)的整个字符串;
    12 print(l[:])  # ==> ['a', 'b', 'c', 'd', 'e']
    13 # [start:]    从start位置提取到结尾
    14 print(l[1:]) # ==> ['b', 'c', 'd', 'e']  l[0]=a 没有打印
    15 # [:end]  开头提取到end-1
    16 print(l[:4]) # ==> ['a', 'b', 'c', 'd']  l[4]=e 没有打印
    17 # [start:end] 从start到end-1
    18 print(l[1:4]) # ==> ['b', 'c', 'd'] l[0],l[4] 没有打印
    19 # [start:end:step] 从start到end-1,每step个字符提取一个
    20 print(l[0:5:2]) # ==>['a', 'c', 'e']

     3.5、列表查询

    # list.index(value,[star,[stop]])

    '''
    index(...)
        L.index(value, [start, [stop]]) -> integer -- r
        Raises ValueError if the value is not present.
    
    # 通过值value,从指定的区间查找列表内的元素是否匹配,匹配到第一个则返回索引号;匹配不到则报错ValueError    
    '''
    print(l.index('a',0,4)) # ==>0  在列表0到4之间匹配字符'a',匹配到则返回index号0;

    # list.count(value) ==>返回列表中匹配value的次数

    # 注意:index和count方法的时间复杂度都是O(n),n为列表的规模,随着规模越来越大,则效率越来越慢;

    3.6、列表元素修改

    # list[index]=value  ==>直接对索引位置元素进行赋值(覆盖原来元素)

    #### 给列表增加元素的方法#####
    #
    append方法 append(self, p_object) """ L.append(object) -> None -- append object to end """ # insert方法 insert(self, index, p_object) """ L.insert(index, object) -- insert object before index """ # extend方法 extend(self, iterable) """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
    ## 删除元素方法
    pop方法
    pop(self, index=None)
    """
            L.pop([index]) -> item -- remove and return item at index (default last).
            Raises IndexError if list is empty or index is out of range.
    """
    remove方法
    remove(self, value)
    """
            L.remove(value) -> None -- remove first occurrence of value.
            Raises ValueError if the value is not present.
    """

    #  '+'  ==> list

      连接操作,将2个列表连接起来

      产生新的列表,原列表不变,本质上是调用了__add__()方法;

    # ‘*’  ==> list

      重复操作,将本列表元素重复n次,返回新的列表;

    # 关于*的坑
    # 当列表内的元素为数值类型是,*则为简单的重复
    l1=[1,2,3]
    #
    # print(l1*3) # ==> [1, 2, 3, 1, 2, 3, 1, 2, 3]
    
    # 当列表内有引用数据类型的时候,* 则是复制的引用类型的内存地址;
    l2=[1,2,3,l1]
    l3=l2*3
    print(l2)
    print(l3)
    print('<==================================>')
    
    l2[3][0]=10 print(l3)
    
    '''
    [1, 2, 3, [1, 2, 3]]
    [1, 2, 3, [1, 2, 3], 1, 2, 3, [1, 2, 3], 1, 2, 3, [1, 2, 3]]
    <==================================>
    [1, 2, 3, [10, 2, 3], 1, 2, 3, [10, 2, 3], 1, 2, 3, [10, 2, 3]]
    '''

    3.7、列表的拷贝

    # 深拷贝(deepcopy)与浅拷贝(show copy,默认为浅拷贝)

    # 浅拷贝图解:

    # 深拷贝:实际是把指针的内容也拷贝了一份,拷贝的point和原来的point指向不同的内存空间了;

    # 实现深拷贝需要单独导入copy模块才能使用:copy.deepcopy(object)

     3.8、列表排序,反转

    # reverse()  返回None,将列表元素反转  (返回None,表示直接修改原列表,不会产生新列表)

    # sort(key=None,reverse=False) 返回None,默认为升序排列;

    1 l=[2,354,3,1,78,122]
    2 l.sort()
    3 print(l)
    4 '''
    5 [1, 2, 3, 78, 122, 354]
    6 '''

    3.9、随机数

    # 导入random模块

     1 import random
     2 
     3 # print(random.randint(0,1)) # 返回[a,b]之间的整数
     4 L=[1,2,3,4]
     5 # print(random.choice(l)) # 从非空序列的元素中随机挑选一个元素
     6 print(random.randrange(1,7,2))
     7 random.shuffle(L) # 对列表L进行洗牌操作
     8 print(L) # ==> [3, 2, 4, 1]
     9 
    10 '''
    11 sample(self, population, k)
    12 population:样本空间;
    13 k:取值个数
    14 '''
    15 print(random.sample(L,2)) # 表示从列表L中随机挑选2个数输出 ==> [4, 2]
  • 相关阅读:
    OCP-1Z0-051-V9.02-162题
    OCP-1Z0-051-V9.02-161题
    OCP-1Z0-051-V9.02-160题
    Matlab中矩阵的分解
    OCP-1Z0-051-V9.02-158题
    OCP-1Z0-051-V9.02-157题
    Matlab中特殊的矩阵函数
    求Matlab中矩阵的秩和迹
    Matlab中的条件数
    在android里使用boost c++
  • 原文地址:https://www.cnblogs.com/soulgou123/p/9436057.html
Copyright © 2020-2023  润新知