向列表中添加一个元素:可使用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']
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/81512.html