• python学习九(修改列表)



    序列(sequence)
    - 序列是python中最基本的一种数据架构
    - 数据架构指计算机中数据储存的方式
    - 序列的分类:
    可变序列(序列中的元素可以改变):
    > 列表(list)

    不可变序列(序列中的元素不可改变):
    > 字符串(str)
    > 元祖(tuple)

    修改元素(只适用于可变序列)
    stus = ["a", "b", "c", "d", "e"]
    修改列表中的元素,直接通过索引来修改元素
    stus[0] = "A"
    print(stus) # 将列表中的a修改为A

    可以通过del来输出元素
    del stus[2]
    print(stus) # 将列表中的删除

    stus = ["a", "b", "c", "d", "e"]
    通过切片来修改列表, 在给切片进行赋值时,只能使用序列
    stus[0:2] = "AB"
    print(stus) # 将列表中的ab修改为AB
    stus[0:0] = "Z"
    print(stus) # 在索引为0的元素前面插入元素

    stus = ["a", "b", "c", "d", "e"]
    通过切片来删除元素
    del stus[0:2]
    print(stus) # 将ab删除

    通过方法来修改元素
    stus = ["a", "b", "c"]
    使用append()添加元素
    stus.append(d)
    print(stus) # 将d添加到列表的最后

    使用insert()向列表指定的位置添加元素
    参数:
    1.要插入的位置
    2.要插入的元素
    stus.insert(2, "z")
    print(stus) # 在列表中的第二个元素位置插入z元素

    使用extend()使用新的序列扩展当前序列,需要一个序列作为参数,它会将序列中的元素添加到当前列表中
    suts.extend(["x", "z"])
    print(stus)

    使用clear()清空序列
    stts.clear()
    print(stus)

    stus = ["a", "b", "c"]
    使用pop()根据索引删除并返回指定元素
    stus.pop(2)
    print(stus) # 删除索引为2的元素,如果不写参数默认删除最后一个

    stus = ["a", "b", "c"]
    使用remover()删除指定的元素
    stus.remover("a")
    print(stus) # 删除指定的元素a,如果相同的值有多个就删除第一个a元素

    stus = list("143256789")
    使用sort()对列表进行升序排列
    stus.sort()
    print(stus)
    如果需要降序排列使用参数reverse = True
    stus.sort(reverse=True)
    print(stus)

    stus = ["a", "b", "c"]
    使用reverse()用来反转列表
    stus.sort()
    print(stus) # 获得cba

    遍历列表
    遍历列表,指将列表中的元素取出来
    stus = ["a", "b", "c", "d", "e"]
    通过while循环来遍历列表:
    i = 0
    while i < len(stus):
    print(stus[i])
    i += 1

    通过for循环来遍历列表
    语法:
    for 变量 in 序列:
    代码块

    for i in stus:
    print(i)
  • 相关阅读:
    文件复制
    linux 计划任务
    mysql查询权限的用户名密码
    mysql导入导出及复制
    windowslucene安装配置
    apache+php32位平台安装
    文件移动
    mysql查询权限的用户名密码
    取树状结构的某个值下的所有记录
    今天发生了个有趣的排序
  • 原文地址:https://www.cnblogs.com/wangwen022/p/11302844.html
Copyright © 2020-2023  润新知