列表
列表由一系列特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。
#在Python中,用方括号来表示列表,并用逗号来分隔其中的元素
bicycles=['trck','cannondale','redline','speclialized']
print(bicycles)
#输出包括方括号['trck', 'cannondale', 'redline', 'speclialized']
访问列表元素
列表是 有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。在python中,第一个列表元素的索引为0,而不是1.Python为访问最后一个元素提供了一种特殊语法。通过将索引指定为-1,可让Python返回最后一个元素。
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[0].upper())
trck
Trck
TRCK
修改列表元素:可指定列表名和要修改的元素索引,再指定该元素的新值。
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0]='ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
在列表中添加元素(使用方法append(),将元素添加到列表末尾)
motorcycles=['honda','yamaha','ducati']
#print(motorcycles)
motorcycles.append('suzuki')
print(motorcycles)
#['ducati', 'yamaha', 'suzuki', 'suzuki']
在列表中 插入元素(使用方法insert()可在列表的任何位置添加新元素)
motorcycles.insert(0,'hello')
print(motorcycles)
#['hello', 'ducati', 'yamaha', 'suzuki', 'suzuki']
从列表中删除元素
使用del语句删除元素:
del motorcycles[0]#如果知道要删除的元素在列表中的位置,可使用del语句
print(motorcycles)
#['ducati', 'yamaha', 'suzuki', 'suzuki']
使用方法pop()删除
motorcycles=['honda','yamaha','suzuki']#方法pop()可删除列表表尾的元素,并让你能够接着使用它
print(motorcycles)
popped_motrcycles=motorcycles.pop()
print(motorcycles)
print(popped_motrcycles)
#['honda', 'yamaha', 'suzuki']
#['honda', 'yamaha']
#suzuki
也可以使用pop()来删除列表中任意位置的元素,只需要在括号中指定要删除的元素索引即可
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
first_owned=motorcycles.pop(0)
print(first_owned)
根据值删除元素:有时候你不知道从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.remove('honda')
print(motorcycles)