1. 列表是什么 由一系列按特定順序排列的元素組成,在Python中,用方括號([] )來表示列表,并用逗號來分隔其中的元素。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']PRint(bicycles)(1). 訪問列表元素 要訪問列表的任何元素,只需將該元素的位置或索引告訴Python即可,索引從0而不是1開始。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[0])(2). 訪問最后一個列表元素,通過將索引指定為-1
bicycles = ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[-1])2. 修改、添加和刪除元素 (1). 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles[0] = 'ducati'print(motorcycles)(2). 在列表中添加元素 在列表末尾添加元素,append()
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles.append('ducati')print(motorcycles)在任何位置插入元素,insert(n) 方法insert() 在索引n 處添加空間,并將值存儲到這個地方。這種操作將列表中既有的每個元素都右移一個位置.
(3). 從列表中刪除元素 使用del 可刪除任何位置處的列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)del motorcycles[0]print(motorcycles)使用方法pop() 刪除列表末尾元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)popped_motorcycle = motorcycles.pop()print(motorcycles)print(popped_motorcycle)彈出列表中任何位置處的元素,pop(n)
motorcycles = ['honda', 'yamaha', 'suzuki']first_owned = motorcycles.pop(0)print('The first motorcycle I owned was a ' + first_owned.title() + '.')如果你不確定該使用del 語句還是pop() 方法,下面是一個簡單的判斷標準:如果你要從列表中刪除一個元素,且不再以任何方式使用它,就使用del 語句;如果你要在刪除元素后還能繼續使用它,就使用方法pop()
根據值, 刪除元素,remove()
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']print(motorcycles)motorcycles.remove('ducati')print(motorcycles)使用remove() 從列表中刪除元素時,也可接著使用它的值。 注意 方法remove() 只刪除第一個指定的值。如果要刪除的值可能在列表中出現多次,就需要使用循環來判斷.
3. 組織列表 (1). 使用方法sort() 對列表進行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort()print(cars)(2). 反向排序,只需向sort() 方法傳遞參數reverse=True 。
cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort(reverse=True)print(cars)(3). 使用函數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)(4). 反轉列表,reverse() 要反轉列表元素的排列順序,可使用方法reverse()
cars = ['bmw', 'audi', 'toyota', 'subaru']print(cars)cars.reverse()print(cars)方法reverse() 永久性地修改列表元素的排列順序
4. 確定列表的長度 使用函數len() 可快速獲悉列表的長度
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']>>> len(cars)4新聞熱點
疑難解答