目录
3.1 列表是什么
列表由一系列按特定顺序排列的元素组成。其中元素之间没有任何关系。
如果让Python将列表打印出来,Python将打印列表的内部表示,包括方括号。
3.1.1 访问元素列表
需要告诉Python该元素的位置(索引)
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[0])#输出trek
3.1.2 索引从0而不是从1开始
大多数编程语言是如此规定的,这与列表操作的底层实现有关。
3.1.3 使用列表中的各个值
你可以像使用其他变量一样使用列表中的各个值。例如,可以使用f字符串根据列表中的值来创建消息。
bicycles=['trek','cannondale','redline','specialized']
message=f"My first bicycle was a {bicycles[0].title()}."
print(message)#输出My first bicycle was a Trek.
3.2 修改、添加和删除元素
3.2.1 修改列表元素
bicycles=['trek','cannondale','redline','specialized']
bicycles[0]='ducati'
print(bicycles)#输出['ducati','cannondale','redline','specialized']
3.2.2 在列表中添加元素
1.在列表末尾添加元素:使用 append() 方法
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)#输出['honda','yamaha','suzuki']
motorcycles.append('ducati')
print(motorcycles)#输出['honda','yamaha','suzuki','ducati']
2.在列表中插入元素:使用 insert() 方法
motorcycles=['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)#输出['ducati','honda','yamaha','suzuki']
3.2.3 从列表中删除元素
1.使用del语句删除元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)#输出['honda','yamaha','suzuki']
del motorcycles[0]
print(motorcycles)#输出['yamaha','suzuki']
2.使用pop()方法删除元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)#输出['honda','yamaha','suzuki']
popped_motorcycle=motorcycles.pop()
print(motorcycles)#输出['honda','yamaha']
print(popped_motorcycle)#输出suzuki
3.删除列表中任意位置的元素:使用pop()方法
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)#输出['honda','yamaha','suzuki']
first_motorcycle=motorcycles.pop(0)
print(motorcycles)#输出['yamaha','suzuki']
print(first_motorcycle)#输出honda
4.根据值删除元素:使用 remove() 方法
motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)#输出['honda','yamaha','suzuki','ducati']
too_expensive='ducati'
motorcycles.remove(too_expensive)
print(motorcycles)#输出['honda','yamaha','suzuki']
print(f"\nA{too_expensive.title()} is too expensive for me.")#输出A Ducati is too expensive for me.
注意:remove()方法只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环,确保将每个值都删除。这将在第7章中介绍。
3.3 管理列表
3.3.1 使用sort()方法对列表进行永久排序
3.3.2 使用sorted()函数对列表进行临时排序
3.3.3 反向打印列表
3.3.4 确定列表的长度:使用 len() 函数
motorcycles=['honda','yamaha','suzuki','ducati']
print(len(motorcycles))#输出4