1、定义
1、列表由一系列按特定顺序排列的元素组成,,用方括号([])来表示列表,并用逗号来分隔其中的元素。
可以将任何东西加入列表中,其中的元素之间可以没有任何关系。 列表通常包含多个元素,最好给列表指定一个表示复数的名称(如letters、digits或names)
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
2、访问列表元素
要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
trek
2、第一个列表元素的索引为0,而不是1
通过将索引指定为-1,可让Python返 回最后一个列表元素:
索引-2返回倒数第二个列表元素, 索引-3返回倒数第三个列表元素,以此类推。
2、列表基础操作
1、修改列表元素,可指定列表名和要修改 的元素的索引,再指定该元素的新值。
motorcycles[0] = 'ducati'
2、添加元素
在列表末尾添加元素 ,方法append()。
motorcycles.append('ducati')
print(motorcycles)
方法append()让动态地创建列表易如反掌,例如,你可以先创建一个空列表,再使用一系列的 append()语句添加元素。
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
3、插入元素 使用方法insert()可在列表的任何位置添加新元素,需要指定新元素的索引和值。
这种操作将列表中既有的每个元素都右移一个位置
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']
4、删除元素
a、使用del语句删除元素 如果知道要删除的元素在列表中的位置,可使用del语句。
del motorcycles[0]
b、方法pop()可删除列表末尾的元素,并让你能够 接着使用它。
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
c、可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素 的索引即可。
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
d、只知道要删除的元素的值,可使 用方法remove()。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要 使用循环来判断是否删除了所有这样的值。
3、组织列表
1、使用方法 sort()对列表进行永久性排序 ,再也无法恢复到原来的排列顺序。
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
按与字母顺序相反的顺序排列列表元素,为此,只需向sort()方法传递参数 reverse=True
cars.sort(reverse=True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
2、使用函数 sorted()对列表进行临时排序
如果你要按与字母顺 序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。
注
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again: ['bmw', 'audi', 'toyota', 'subaru']
3、要反转列表元素的排列顺序,可使用方法reverse()
方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序
4、使用函数len()可快速获悉列表的长度