栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python之列表中常用的函数:append,extend,insert,pop,remove,del函数的定义与使用方法,元素是否在列表中的判断

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python之列表中常用的函数:append,extend,insert,pop,remove,del函数的定义与使用方法,元素是否在列表中的判断

向列表中添加一个元素:可使用append,extend,insert函数直接实现。

append函数:将需要添加的元素添加到该列表的末位置。列表名.append(需要添加的元素)
举例:

list1=["apple","banana","orange","vegetable","beef"]
print("添加之前:")
print(list1)
list1.append("dog")
print("添加之后:")
print(list1)
添加之前:
['apple', 'banana', 'orange', 'vegetable', 'beef']
添加之后:
['apple', 'banana', 'orange', 'vegetable', 'beef', 'dog']

extend函数:将需要添加的元素先进行拆分,再添加到原列表的末位置。列表名.extend(需要添加的元素)
举例:

list1=["apple","banana","orange","vegetable","beef"]
print("添加之前:")
print(list1)
list1.extend("dog")
list1.extend("你好")
list1.extend("1234")
print("添加之后:")
print(list1)
添加之前:
['apple', 'banana', 'orange', 'vegetable', 'beef']
添加之后:
['apple', 'banana', 'orange', 'vegetable', 'beef', 'd', 'o', 'g', '你', '好', '1', '2', '3', '4']

insert函数:向原列表中插入元素。列表名.insert(插入的位置,插入的元素)
举例:

list1=["apple","banana","orange","vegetable","beef"]
print("添加之前:")
print(list1)
list1.insert(1,"dog")
list1.insert(2,"people")
print("添加之后:")
print(list1)
添加之前:
['apple', 'banana', 'orange', 'vegetable', 'beef']
添加之后:
['apple', 'dog', 'people', 'banana', 'orange', 'vegetable', 'beef']
查找某个元素是否在列表中:if 查找的元素变量名 in/not in 列表:

举例:

nameList = ["xiaoming","xiaoli","xiaowang","xiaoli"]
name= input('请输入你要查找的姓名:')
if name not in nameList:
    print('%s不存在'%name)
else:
 print('%s存在'%name)
请输入你要查找的姓名:Jason
Jason不存在
列表元素的删除:可通过del,pop,remove函数实现。

del函数 :通过下标删除某个元素。
举例:

nameList = ["xiaoming","xiaoli","xiaowang","xiaoli"]
del nameList[2]
print(nameList)
['xiaoming', 'xiaoli', 'xiaoli']

pop函数:删除列表最后一个元素。
举例:

nameList = ["xiaoming","xiaoli","xiaowang","xiaoli"]
nameList.pop()
print(nameList)
['xiaoming', 'xiaoli', 'xiaowang']

remove函数:将某个元素在列表中移除。
举例:

nameList = ["xiaoming","xiaoli","xiaowang","xiaoli"]
nameList.remove("xiaoming")
print(nameList)
['xiaoli', 'xiaowang', 'xiaoli']
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979687.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号