列表基本的操作,添加修改和删除。
1.列表元素的创建和访问
codeArray=['Java','C#','python']
codeArray[0]
索引从0开始,另外索引可以写负数,标识为倒序索引,即-1表示倒数第一个元素,以此类推。2.修改元素
#3.2.1修改元素
motorcycles=['honda','yamaha','suzuki']
motorcycles[0]='ducati'
3.删除元素
三种方法删除
#del 方式
motorcycles=['honda','yamaha','suzuki']
del motorcycles[0]#这个索引可以为负数,为倒数第几个
print(motorcycles)
#pop()可获取删除的元素值
motorcycles1=['honda','yamaha','suzuki']
print(motorcycles1)
poped_motorcycles=motorcycles1.pop()
print('删除了索引0的元素'+poped_motorcycles)
#pop(index)可以删除index处的元素可以为负数
motorcycles2=['honda','yamaha','suzuki']
poped_motorcycles=motorcycles2.pop(-1)
print('删除了索引-1的元素'+poped_motorcycles)
#remove()根据元素值删除元素,
motorcycles3=['honda','yamaha','suzuki','ducati']
print(motorcycles3)
motorcycles3.remove('ducati')
print(motorcycles3)
使用del方式和pop()方式的区别在于,pop()可以获取删除元素的值,而del方式不可以
另外remove()方法,需要注意的是删除方remove()这个只会移除一次列表指定值,如要移除所有还要重复删除和判断。
# 只删除第一个指定的值。
motorcycles=['honda','yamaha','suzuki','ducati','ducati'] #这里我们有2个ducati值
print(motorcycles)
motorcycles.remove('ducati')#移除一次
print(motorcycles) # 结果为['honda','yamaha','suzuki','ducati']
motorcycles.remove('ducati')#再次移除
print(motorcycles) # 结果为['honda','yamaha','suzuki']