# 列表 由一系列按特定顺序排列的元素组成。 bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) # 访问列表元素 print(bicycles[0]) print(bicycles[0].title()) # 索引从0而不是1开始 print(bicycles[1]) print(bicycles[3]) print(bicycles[-1]) # 访问最后一个; # 使用列表中的各个值 message = "My first bicycle was a " + bicycles[0].title() + "." print(message) # 修改、 添加和删除元素 # 修改列表元素 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) # 在列表中添加元素 motorcycles.append('ducati') # 在列表末尾添加元素 print(motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles.insert(0, 'ducati') # 在列表中插入元素 print(motorcycles) # 从列表中删除元素 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[0] # 使用del 语句删除元素 print(motorcycles) del motorcycles[1] print(motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) popped_motorcycle = motorcycles.pop() # 使用方法pop() 删除元素 print(motorcycles) print(popped_motorcycle) first_owned = motorcycles.pop(0) # 弹出列表中任何位置处的元素 print('The first motorcycle I owned was a ' + first_owned.title() + '.') # 如果你要从列表中删除一个元素, 且不再以任何方式使用它, 就使用del 语句; # 如果你要在删除元素后还能继续使用它, 就使用方法pop() 。 motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) motorcycles.remove('ducati') # 根据值删除元素 print(motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) too_expensive = 'ducati' motorcycles.remove(too_expensive) print(motorcycles) print("\nA " + too_expensive.title() + " is too expensive for me.") # 方法remove() 只删除第一个指定的值。 如果要删除的值可能在列表中出现多次, 就需要使用循环来判断是否删除了所有这样的值。 cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() # 使用方法sort() 对列表进行永久性排序 print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] print("\nHere is the original list:") print(cars) # 使用函数sorted() 对列表进行临时排序 print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse() # 倒着打印列表 print(cars) print(len(cars)) # 确定列表的长度

浙公网安备 33010602011771号