python列表中删除元素的三种方法

Python (162) 2023-04-16 04:24:21

python列表中删除元素的三种方法

方法一:使用del语句删除元素(前提是知道要删除的元素的位置)

bicycles=['trek','cannondale','redline','specialized']
print('删除前')
print(bicycles)

print('删除后')
delbicycles[1]
print(bicycles)

输出

删除前
['trek','cannondale','redline','specialized']
删除后
['trek','redline','specialized']

方法二:使用pop()方法删除列表末尾的元素

>>>listA=['a','b','c','a','b','c','a','b','c']
>>>w=listA.pop(3)
>>>w
'a'
>>>print(listA)
['a','b','c','b','c','a','b','c']

方法三:使用remove()方法根据值删除元素

bicycles=['trek','cannondale','redline','specialized']
print(bicycles)


bicycles.remove('cannondale')
print(bicycles)

输出

['trek','cannondale','redline','specialized']
['trek','redline','specialized']
THE END

发表回复