zoukankan      html  css  js  c++  java
  • python 列表(List)

    列表是由一系列按特定顺序的元素组成。

    列表是有序集合,当我们需要访问列表中的某一元素时,只需要将该元素的位置或索引告诉python即可,第一个索引是从0开始,依次类推

    在python中,用来表示列表,并用逗号来分隔其中的元素

    1.列表常用的独有的方法

    (1)append()方法

    方法/参数 备注
    方法:append( “content" ) 在列表后面添加元素
    参数:content 需要插入的元素
    list = []
    list.append( "Maple" )
    list.append( "yf" )
    list.append( "hao" )
    print(list)
    
    #输出的结果如下:
    ['Maple', 'yf', 'hao']
    

    (2)insert()方法

    方法/参数 备注
    方法:insert( index, content ) 在index前插入指定的元素(content)
    参数:index 需要在哪个索引的位置
    参数:content 需要插入的元素
    list = ["Maple", "yf", "hao","123"]
    
    list.insert(2,"study")
    
    print(list)
    
    #输出的结果如下:
    ['Maple', 'yf', 'study', 'hao', '123']
    

    (3)pop()方法

    方法/参数 备注
    方法:pop( [index] ) 将指定索引位置的元素删除,并返回删除元素的值
    不指定索引位置,默认从删除列表最后一个元素
    参数:index 元素的索引位置
    list = ["Maple", "yf", "hao","123"]
    
    list.pop(1)
    
    print(list)
    
    #输出的结果如下:
    ['Maple', 'hao', '123']
    

    (4)remove()方法

    参数/方法 备注
    方法:remove( "content" ) 将指定的元素删除
    参数:content 元素的值
    list = ["Maple", "yf", "hao","123"]
    
    list.remove( "hao" )
    
    print(list)
    
    #输出的结果如下:
    ['Maple', 'yf', '123']
    

    (5)clear()方法

    参数/方法 备注
    clear() 将列表的内容清空
    list = ["Maple", "yf", "hao","123"]
    
    list.clear()
    
    print(list)
    
    #输出的结果如下:
    []
    

    2.公共方法

    (1)len方法

    len()方法:可以用来获得列表有几个元素

    list = ["Maple", "yf", "hao","123"]
    
    print( len(list) )
    
    #输出的结果如下:
    4
    

    (2)切片

    用于获取指定的元素或多个元素

    list = ["Maple", "yf", "hao","123"]
    
    print( list[0:2] )
    
    #输出的结果如下:
    ['Maple', 'yf']
    

    (3)索引

    获取指定的索引的元素

    list = ["Maple", "yf", "hao","123"]
    
    print( list[2] )
    
    #输出的结果如下:
    hao
    

    (4)del删除

    删除指定元素

    list = ["Maple", "yf", "hao","123"]
    
    del list[2]
    
    print( list )
    
    #输出的结果如下:
    ['Maple', 'yf', '123']
    

    (5)步长

    list = ["Maple", "yf", "hao","123"]
    
    print( list[0:2:2])
    
    #输出的结果如下:
    ['Maple']
    

    (6)修改

    list = ["Maple", "yf", "hao","123"]
    
    list[2] = "您好"
    
    print(list)
    
    #输出的结果如下:
    ['Maple', 'yf', '您好', '123']
    

    (7)for循环

    list = ["Maple", "yf", "hao","123"]
    
    for item in list:
        print(item)
        
    #输出的结果如下:
    Maple
    yf
    hao
    123
    
  • 相关阅读:
    关于PCA主成分分析的一点理解
    python前言
    python
    unitest单元测试TestCase 执行测试用例(二) 断言
    python基础
    python-requests中get请求接口测试
    python数据类型字典和集合
    python数据类型 列表+元组
    函数是什么?函数式编程
    sql常用
  • 原文地址:https://www.cnblogs.com/Heroge/p/13196458.html
Copyright © 2011-2022 走看看