python列表基本操作

列表的基本操作示例展示:

append

    功能:列表追加元素
    name = ['sd','dfdf','drer']
    name.append('sdsd')
    返回结果:name
            ['sd', 'dfdf', 'drer', 'sdsd']

clear

    功能:情况列表元素
    name = ['sd','dfdf','drer']
    name.clear()
    返回结果:name
             []

copy

    功能:浅拷贝,即只拷贝第一层的元素
    name = ['sd','dfdf','drer']
    li = ['ssd']
    li = name.copy()
    返回结果:li
             ['sd', 'dfdf', 'drer']

    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    li = ['ssd']
    li = name.copy()
    返回结果:li
    ['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd']]

count

    功能:统计列表指定元素个数
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.count('sd')
    返回结果:1
    li = ['sd','sdsds',['sd','dffdg',],]
    li.count('sd') #只统计第一层的元素个数
    返回结果:1

extend

    功能:追加字符元素或列表元素
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    li = ['sd','sdsds',['sd','dffdg',],]
    name.extend('ss')
    返回结果:name
    ['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's']
    name.extend('d')
    返回结果:name
    ['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's', 'd']
    name.extend(li)
    返回结果:name
    ['sd', 'dfdf', 'drer', ['sddss', 'sdsdsd'], 's', 's', 'd', 'sd', 'sdsds', ['sd', 'dffdg']]

index

    功能:定位列表中某元素
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.index('sd')
    返回结果:0
    name.index('drer')
    返回结果:2
    返回结果:name.index('dr')  #当出现某元素不在列表中的时候会直接报错
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            ValueError: 'dr' is not in list

insert

    功能:在指定索引位置的元素前面插入新的元素
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.insert(3,'sd')
    返回结果:name
    ['sd', 'dfdf', 'drer', 'sd', ['sddss', 'sdsdsd']]

pop

    功能:删除指定索引值的元素,返回值为当前删除的元素的值。不指定索引值,默认删除最后一个元素
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.pop(3)
    返回结果:'sd'

remove

    功能:删除列表中指定的元素
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.remove('sd')
    name
    返回结果:['dfdf', 'drer', ['sddss', 'sdsdsd']]

reverse

    功能:用于反向列表中元素。
    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.reverse()
    name
    返回结果:[['sddss', 'sdsdsd'], 'drer', 'dfdf', 'sd']
    

sort

    功能:对单层列表进行元素的排序
    name = ['sd','dfdf','drer',]
    name.sort()
    name
    返回结果:['dfdf', 'drer', 'sd']

    name = ['sd','dfdf','drer',['sddss','sdsdsd']]
    name.sort() #报错的
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

python列表基本操作