文章目录[隐藏]
motocycles = [ 'honda' , 'yamaha' , 'suzuki' ]
1.更改列表:
motocycles [0] = 'ducati'
print (motocycles)
2.在列表中编辑元素
1. 使用append 在后面直接添加新元素
motocycles.append('ducati')
print(motocycles)
2.使用 insert 指定插入的元素和索引
motocycles.insert(0,'ducati')
print(motocycles)
3.使用 del 删除某个元素
del motocycles[0]
# 此时在索引0中的内容将会被删除,后面的部分依次向前移位
4.使用 pop() 删除元素
popped_motocycles = motocycles.pop()
print(motocycles)
print(popped_motocycles)
# 此时列表将会从最后一个向前依次删除, pop()中的数值可以被定义为索引,缺省则为从后向前
5. 使用 Remove 在不使用索引的情况下删除内容
motocycles.remove('ducati')
print(motocycles)
# 此时列表中的某一项将会被直接删除
删除时使用外部参数
too_expansive = "ducati"
motocycles.remove(too_expansive)
print(motocycles)
注意:remove() 只能删除第一个在列表中第一个出现的指定值,如果在列表中含有多次相同值,就需要使用循环来删除。