python基础知识整理列表操作(二)
------ 列表介绍------
列表:由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中
用方括号([] )来表示列表,并用逗号来分隔其中的元素
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
print(bicycles)
访问列表元素
列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
print(bicycles[0])
切片中的索引从0开始不是1…切片取左不取右
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
print(bicycles[1])
print(bicycles[3])
切片特殊用法倒着数从-1开始
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
print(bicycles[-1])
print(bicycles[3])
print(bicycles[:])
切片取左不取右
print(bicycles[:1])
print(bicycles[:2])
使用列表里的值
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]
message = "My first bicycle was a " + bicycles[0].title() + “.”
print(message)
修改列表里面元素
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles)
motorcycles[0] = ‘ducati’
print(motorcycles)
在列表后面贴加元素
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles)
motorcycles.append(‘ducati’)
print(motorcycles)
motorcycles = []
motorcycles.append(‘honda’)
motorcycles.append(‘yamaha’)
motorcycles.append(‘suzuki’)
print(motorcycles)
在列表中插入元素
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
motorcycles.insert(0, ‘ducati’)
print(motorcycles)
从列表里面删除元素
使用del 可删除任何位置处的列表元素,条件是知道其索引
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles)
del motorcycles[0]
print(motorcycles)
从列表里面删除最后一个元素
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
根据值删除元素
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]
print(motorcycles)
motorcycles.remove(‘ducati’)
print(motorcycles)
使用方法sort()对列表进行永久性排序(根据字母顺序排的)
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort()
print(cars)
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort(reverse=True)
print(cars)
使用函数sorted() 对列表进行临时排序
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)
要反转列表元素的排列顺序,可使用方法reverse()
reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(cars)
cars.reverse()
print(cars)
使用函数len() 可快速获悉列表的长度
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(len(cars))