zoukankan      html  css  js  c++  java
  • Python 列表(详)

    Python列表

    列表操作

    定义:list(此处为列表名字) = [(这里写列表元素,用" "包含,逗号隔开,如)“a”,“b”]
    students = [“Linda”,“bob”,“Alice”,“Alen”]
    通过下标可以访问列表的值。从0开始计数。
    students[0] -------> linda
    students[1] -------> bob
    students[2] -------> Alice
    students[3] -------> lAlen

    列表切片操作

    students = [“Linda”,“bob”,“Alice”,“Alen”,“John”]
    students[1:4] #取下标1至下标4之间的值,包括1不包括4
    students[1:-1] #取下标1至下标-1之间的值,包括1不包括-1
    students[0:3] #取下标0至下标3之间的值,包括0不包括3
    students[:3] = students[0:3] #从0开始,0可以忽略
    students[4:] #取列表最后一个元素,只能写最后一个开始,不可以写-1
    students[0:] students[:] #取列表中所有元素
    students[2:-1] #-1没有包含
    students[0::2] #表示每间隔一个元素取一个
    students[::2] #0可以省略

    列表末尾追加元素:

    students = [“Linda”,“bob”,“Alice”,“Alen”,“John”]
    students.append(" 我是新同学")
    列表中插入元素:insert
    students.insert(2,“小明”) #在第2个位置插入小明,其他元素向后移动一位
    [“Linda”,“bob”,“小明”,“Alice”,“Alen”,“John”]
    students.insert(5,“小李”) #在第5个位置插入小李,其他元素向后移动一位
    [“Linda”,“bob”,“小明”,“Alice”,“Alen”,“小李”,“John”]

    修改列表元素:

    只需要修改对应位置的值就可以

    students = ["Alice","Linda","bob","Alice","Alen","John"]
    print(students)
    students[2] = "Bob"
    print(students)
    

    在这里插入图片描述
    删除列表元素:有三种删除列表元素的方法
    1.del
    2.remove
    3.pop

    students = ["Alice","Linda","bob","Alice","Alen","John"]
    del students[1]              #删除对应下标的元素
    print(students)
    students.remove("Alen")      #删除指定元素
    print(students)
    students.pop()               #删除列表最后一个元素
    print(students)
    

    在这里插入图片描述

    列表扩展:

    列表扩展指令为extend

    students = ["Alice","Linda","bob","Alice","Alen","John"]
    print(students)
    studentsnumber = [1,2,3,4,5]
    students.extend(studentsnumber)
    print(students)
    

    在这里插入图片描述
    *

    列表拷贝

    *copy,深copy,浅copy等前面博文已写,不再赘述

    统计(计数):count 计算列表中同一个元素出现的次数

    students = ["Alice","Linda","bob","Alice","Alen","John","Alice"]
    print(students.count("Alice"))
    print(students.count("bob"))
    

    在这里插入图片描述

    排序&翻转

    sort,reverse

    students = ["Alice","Linda","bob","Alice","Alen","John","Alice","!","1","2","4","3"]
    print(students)
    students.sort()     #python3.0不支持不同元素类型的数据排序,会报错,后面的数字和标点应			   该加“”
    print(students)
    students.reverse()
    print(students)
    

    在这里插入图片描述

    获取元素下标:

    students = ["Alice","Linda","bob","Alice","Alen","John","Alice","!","1","2","4","3"]
    
    print(students.index("bob"))
    print(students.index("Alice"))      #有多个元素,只会显示第一个元素的下标
    
    

    在这里插入图片描述

  • 相关阅读:
    hdu 5007 水题 (2014西安网赛A题)
    hdu 1698 线段树(成段替换 区间求和)
    poj 3468 线段树 成段增减 区间求和
    hdu 2795 公告板 (单点最值)
    UVaLive 6833 Miscalculation (表达式计算)
    UVaLive 6832 Bit String Reordering (模拟)
    CodeForces 124C Prime Permutation (数论+贪心)
    SPOJ BALNUM (数位DP)
    CodeForces 628D Magic Numbers (数位DP)
    POJ 3252 Round Numbers (数位DP)
  • 原文地址:https://www.cnblogs.com/candlia/p/11919621.html
Copyright © 2011-2022 走看看