1.2 python的list操作

    技术2023-04-05  85

    1.2 python的list操作

    1.2.1 python基础程序输出注释创建写入txt文档变量 1.2.2 python中的number数据类型number的具体数据类型math模块 1.2.3 列表列表的构建及索引列表的构建列表的索引列表的切片 列表元素的增删改操作列表的新增操作列表的改操作列表的删除操作 列表推导式补充:for循环的格式使用for循环构建列表列表推导式代替for循环构建列表

    1.2.1 python基础程序

    输出

    输出

    print('hello world')

    结果

    hello world

    注释

    单行注释

    # 这是单行注释

    多行注释

    ''' 这是使用三个单引号的多行注释 ''' """ 这是使用三个双引号的多行注释 """

    创建写入txt文档

    string = 'hello world' f = open('hello.txt', 'w') # 以写的方式打开文件 f.write(string) # 将字符串写入被打开的文件中 f.close() # 关闭文件

    但是,open()函数有什么作用呢,参数需要传什么呢?我们可以通过按住Ctrl,点击此函数试试 python中给出的字母表的意思

    ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= ===============================================================

    简单翻译一下

    “r” 只读(默认) “w” 可写入 “x” 创建一个新文件并打开它进行写入 “a” 打开进行写入,如果文件存在,则将其附加到文件末尾 “b” 以二进制模式打开 “t” 以文本模式打开(默认) “+” 打开磁盘文件进行更新(读写) “U” 通用换行模式(已弃用)

    变量

    Python 中的变量不需要声明,每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

    变量一般由字母、数字和下划线组成;通常第一个字符是字母或下划线‘_’;区分大小写,python3 支持中文变量。

    1.2.2 python中的number数据类型

    python中的标准数据类型

    number的具体数据类型

    math模块

    常用的函数如果想使用math中的其他函数但又不知道具体的函数名称时,可以通过math.查看

    1.2.3 列表

    列表的构建及索引

    列表的构建

    all_in_list = [0.3, 'hello', True]

    列表的索引

    # 取第一个元素 res = all_in_list[0] # 取倒数第二个元素 res = all_in_list[-2]

    all_in_list[?]如何确定?呢?我们一起来看看。 假设第一行是我们所创建的列表的内容,则 第二行、第三行是?可以取的值。 我们可以发现,如果想取正数第N个数,?= N - 1 ,或者想取倒数第N个数 ?= -N

    列表的切片

    res = all_in_list[0:2] # 列表的切片,左闭右开,即取出来了all_in_list[0],......,all_in_list[2-1]

    列表元素的增删改操作

    列表的新增操作

    # 新增元素,追加到列表的后边 all_in_list.append('hello world') # 新增元素,添加到0的位置,原先0上的元素以及其后的元素往后移动一位 all_in_list.insert(0,'pre-hello')

    列表的改操作

    all_in_list[0] = 'qwe'

    注意,改后的数据类型与改前的数据类型没有关联,两者的数据类型完全可以不一致

    列表的删除操作

    指定元素的删除

    all_in_list.remove('hello world')

    指定范围的删除

    del all_in_list[:2] del all_in_list[0:2] # 0可以省略

    左闭右开,即删除了all_in_list[0],…,all_in_list[2-1]

    列表推导式

    补充:for循环的格式

    使用for循环构建列表

    x = [] for i in range(10): x.append(i) # print(x) print(x)

    首先构建一个空列表,之后使用循环,往列表中添加元素

    列表推导式代替for循环构建列表

    b = [i for i in range(1,11)] # i的平方,i从110 c = [i**2 for i in range(1,11)] # i的平方,i从110的奇数 d = [i**2 for i in range(1,11) if i%2==0] print(b) print(c) print(d)

    结果

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [4, 16, 36, 64, 100]
    Processed: 0.012, SQL: 9