什么是列表
在python 中用 [ ] 来表示列表,并用逗号来分隔其中元素:
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
其次注意索引是 从0开始而不是从1
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles[0])
下面尝试使用列表中提取第一款汽车,并使用这个值来创建一条消息:
motorcycles = ['honda','yamaha','suzuki']
message = "My first motorcycle was a " + motorcycles[0].title() +"."
print(message)
如何修改 添加 删除元素
关于添加
使用 方法append() 添加元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles.append('ducati')
>>> print(motorcycles)
或者先创建一个空列表,再使用一系列append()语句添加元素:
>>> motorcycles = []
>>> motorcycles.append('honda')
>>> motorcycles.append('yamaha')
>>> motorcycles.append('suzuki')
>>> print(motorcycles)
关于插入
方法 insert() 可在列表的任何位置添加新元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles.insert(0,'ducati')
>>> print(motorcycles)
关于修改
注意第二行语句,利用索引重置定义:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles[0] = 'ducati'
>>> print(motorcycles)
关于删除
- 使用 del语句 删除元素:
>>> motorycles = ['honda','yamaha','suzuki']
>>> del motorcycles[0]
>>> print(motorcycles)
- 使用 方法pop() 删除元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> popped_motorcycle = motorcycles.pop()
>>> print(motorcycles)
实际上,可以使用pop()来删除列表中任何位置的元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> last_owned = motorcycles.pop(2)
>>> print("The last motorcycle I owned was a"+last_owned.title())
- 使用 方法remove() 来根据值删除元素:
>>> motorcycles = ['honda','yamaha','suzuki']
>>> too_expensive = 'yamaha'
>>> motorcycles.remove(too_expensive)
>>> print('A' + too_expensive.title() + 'is too expensive for me.')
注意要点:方法pop()和remove()的共同点在于:在列表中删除元素时,也可以直接使用它的值,与del语句的差别在于:如果要从列表中删除一个元素,那么这个元素以后不再使用。
组织列表
使用 方法sort() 对列表进行 永久性排序 :
>>> cars = ['bmw','audi','toyota','subaru']
>>> cars.sort()
>>> print(cars)
若需要与字母相反的顺序排序:
>>> cars = ['bmw','audi','toyota','subaru']
>>> cars.sort(reverse=ture)
使用 函数sorted() 对列表进行临时排序:
cars = ['bmw','audi','toyota','subaru']
print('Here is the sorted list:')
print(sorted(cars))