国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python -- 2. 列表

2019-11-08 01:35:20
字體:
來源:轉載
供稿:網友

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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铁力市| 喀喇沁旗| 花莲县| 德化县| 武陟县| 论坛| 清水县| 霍州市| 兴业县| 永济市| 滕州市| 南部县| 玉门市| 九寨沟县| 莲花县| 泸州市| 汝城县| 隆安县| 镇赉县| 玉龙| 泽州县| 丹棱县| 通山县| 行唐县| 澄迈县| 钟山县| 遂溪县| 白水县| 邻水| 扶绥县| 福鼎市| 奉化市| 长岭县| 丹寨县| 砀山县| 金昌市| 五寨县| 德兴市| 德兴市| 临武县| 安阳市|