python-列表的增删查改

Posted fltkxy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-列表的增删查改相关的知识,希望对你有一定的参考价值。

转自:https://www.cnblogs.com/liuyam/p/6270062.html

列表是最常用的数据类型之一,通过列表可以对数据实现方便的存储,修改等操作。

先声明一个空列表:

>>> names = []
>>> names
[]

可以存多个值:

>>> names = ["wangwang","maomao"]
>>> names
[wangwang‘, maomao‘]

如何取值:

>>> names[1]
maomao

如何修改:

>>> names[0] = "gougou"
>>> names
[gougou‘, maomao‘]

增加:

>>> names.append("miaomiao")
>>> names
[gougou‘, maomao‘, miaomiao‘]

插入:

>>> names
[gougou‘, maomao‘, miaomiao]
>>> names.insert(2,"new")
>>> names
[gougou‘, maomao‘, new‘, miaomiao‘]

删除:

第一种方法:

>>> names
[gougou‘, maomao‘, new‘, miaomiao]
>>> del names[0]    #根据索引删除
>>> names
[maomao‘, new‘, miaomiao‘]

第二种方法:

>>> names
[maomao‘, new‘, miaomiao]
>>> names.remove("new")    #根据名字删除
>>> names
[maomao‘, miaomiao‘]

查找:

技术分享图片
>>> names
[maomao‘, miaomiao‘, wangwang‘, liyang‘, zhangsi‘, jack‘, mack‘, rain,
yangle‘, wangjie‘, lirun‘, xiaojie]
>>> names.index("liyang")   #查找索引
3
>>> names[3]
liyang‘
>>> names [names.index("liyang")] = "LiYang"  #根据索引重新赋值
>>> names
[maomao‘, miaomiao‘, wangwang‘, LiYang‘, zhangsi‘, jack‘, mack‘, rain,
yangle‘, wangjie‘, lirun‘, xiaojie‘]
技术分享图片

统计某个姓名是否有重名:

>>> names.count("maomao")
2

排序:

技术分享图片
>>> names
[maomao‘, miaomiao‘, wangwang‘, LiYang‘, zhangsi‘, jack‘, mack‘, rain,
yangle‘, wangjie‘, lirun‘, xiaojie‘, maomao]
>>> names.sort()        #根据ASCII排序
>>> names 
[LiYang‘, jack‘, lirun‘, mack‘, maomao‘, maomao‘, miaomiao‘, rain‘, wan
gjie, ‘wangwang, ‘xiaojie, ‘yangle, ‘zhangsi]
技术分享图片

从大到小排序:

>>> names.reverse()
>>> names
[zhangsi‘, yangle‘, xiaojie‘, wangwang‘, wangjie‘, rain‘, miaomiao‘, mao
mao, ‘maomao, ‘mack, ‘lirun, ‘jack, ‘LiYang]

取值:

技术分享图片
>>> names
[zhangsi‘, yangle‘, xiaojie‘, wangwang‘, wangjie‘, rain‘, miaomiao‘, mao
mao, ‘maomao, ‘mack, ‘lirun, ‘jack, ‘LiYang]
>>> names[3:5]   #取第3和第4。注意:切片顾头不顾尾
[wangwang‘, wangjie]
>>> names[-1]。 #取最后一个
LiYang‘
>>> names[-3:-1]  #倒数第三位和倒数第二位,注意永远是从左到右切片的
[lirun‘, jack‘]
技术分享图片

打印所有的基数位:

>>> names
[zhangsi‘, yangle‘, xiaojie‘, wangwang‘, wangjie‘, rain‘, miaomiao‘, mao
mao, ‘maomao, ‘mack, ‘lirun, ‘jack, ‘LiYang]
>>> names[0::2]   #从头到尾,2为步长
[zhangsi‘, xiaojie‘, wangjie‘, miaomiao‘, maomao‘, lirun‘, LiYang‘]

array数组不能修改。

以上是关于python-列表的增删查改的主要内容,如果未能解决你的问题,请参考以下文章

python-列表的增删查改

python中关于list列表的增删查改操作

2017-12-19python全栈9期第四天第二节之列表的增删查改之按切片删除

2017-12-19python全栈9期第四天第二节之列表的增删查改之元祖是只读列表可循环查询可切片儿子不能改孙子可以改

2017-12-19python全栈9期第四天第二节之列表的增删查改之删除的pop和del和remove和clear

python增删查改实例