|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
del函数
如果知道要删除元素在列表中的位置,可以使用del语句:
- list_1 = ['one', 'two', 'three']
- print(list_1)
- del list_1[0]
- print(list_1)
复制代码
根据索引,del语句删除了list_1列表中的第一个元素——'one'
- ['one', 'two', 'three']
- ['two', 'three']
复制代码
要想使用del删除列表中的任意元素,前提是知道其索引(位置)
pop()
pop()顾名思义——弹出,弹出列表末尾的元素,并且使用这个弹出的元素:
- list_1 = ['one', 'two', 'three']
- print(list_1)
- pop_list_1 = list_1.pop()
- print(pop_list_1)
- print(list_1)
复制代码
这里使用pop()弹出了list_1列表的最后一个元素'three',并且把'three'赋值给了pop_list_1
- ['one', 'two', 'three']
- three
- ['one', 'two']
复制代码
当然,pop(索引)也可以弹出列表中的任意元素,前提是知道该元素的索引:
- list_1 = ['one', 'two', 'three']
- print(list_1)
- pop_list_1 = list_1.pop(1)
- print(pop_list_1)
- print(list_1)
复制代码
如del一般,这里弹出了列表的第二个元素(索引为1)
- ['one', 'two', 'three']
- two
- ['one', 'three']
复制代码
remove()
有时候我们不知道元素的索引的时候,但是知道要删除的这个元素是什么,那我们就可以用remove()这个方法
- list_1 = ['one', 'two', 'three']
- print(list_1)
- list_1.remove('two')
- print(list_1)
复制代码
此时我们知道了要删除的元素是'two',那么我们用remove()得:
- ['one', 'two', 'three']
- ['one', 'three']
复制代码
当然,和pop一样,被删除的元素我们依然可以使用:
- list_1 = ['one', 'two', 'three']
- print(list_1)
- remove_1 = 'two'
- list_1.remove(remove_1)
- print(list_1)
- print(remove_1.title())
复制代码
我们先把要删除的元素'two'存储在remove_1中,然后再用remove()方法把remove_1中存储的值删除,但是元素'two'依然存储在变量remove_1中
- ['one', 'two', 'three']
- ['one', 'three']
- Two
复制代码 |
|