python列表函数与列表操作的例子

发布时间:2020-08-07编辑:脚本学堂
python列表操作的常用函数,通过例子学习python列表添加、删除元素与赋值的方法,需要的朋友参考下。

python列表

list函数
list函数将其他类型的序列转换为列表,如
 

>>> list("hello world")
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

列表操作
元素赋值可以改变列表,如
 

>>> sen
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> sen[0] = 'H'
>>> sen
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

使用del从列表中删除元素,如
 

>>> sen
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> del sen[0]
>>> sen
['e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

分片赋值可以一次为多个元素赋值,如
 

>>> sen
['e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> sen[:3] = list("hhhh")
>>> sen
['h', 'h', 'h', 'h', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

分片赋值还可以插入一个序列,如
 

>>> sen = list("world")
>>> sen[0:0] = list("hello ")
>>> sen
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

列表方法
append -- 在列表末尾追加新的对象,直接修改原来的列表
count  --  统计某个元素在列表中出现的次数
extend -- 在列表的末尾一次性追加另一个序列的多个值,直接修改原列表
 

>>> sen = list("world")
>>> sen.extend(list('er'))
>>> sen
['w', 'o', 'r', 'l', 'd', 'e', 'r']

index -- 从列表中找出某个值第一个匹配项的索引位置
 

>>> sen
['w', 'o', 'r', 'l', 'd', 'e', 'r']
>>> sen.index('r')
2

insert -- 将对象插入到列表中

pop -- 移除列表中的一个元素(默认最后一个),并返回该元素的值
 

>>> sen
['w', 'o', 'r', 'l', 'd', 'e', 'r']
>>> sen.pop()
'r'
>>> sen
['w', 'o', 'r', 'l', 'd', 'e']
>>> sen.pop(0)
'w'

NameError: name 'seb' is not defined
>>> sen
['o', 'r', 'l', 'd', 'e']

remove -- 移除列表中某个值的第一个匹配项
 

>>> sen
['o', 'r', 'l', 'd', 'e']
>>> sen.remove('l')
>>> sen
['o', 'r', 'd', 'e']

reverse -- 将列表中的元素返乡存放
sort -- 在原位置对列表进行排序,返回空值
sorted -- 获取已排序的列表副本,此函数用于任何序列
 

>>> sen_sorted = sorted(sen)
>>> sen_sorted
['d', 'e', 'o', 'r']
>>> sen
['o', 'r', 'd', 'e']