国产探花免费观看_亚洲丰满少妇自慰呻吟_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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 钟山县| 高陵县| 普定县| 桂平市| 长泰县| 武汉市| 高要市| 通榆县| 股票| 开远市| 胶南市| 平泉县| 陇西县| 喀喇沁旗| 化隆| 马鞍山市| 江阴市| 荆州市| 丰顺县| 和平县| 焦作市| 永胜县| 比如县| 梁河县| 北川| 安岳县| 崇阳县| 宿州市| 蒲城县| 富顺县| 信阳市| 阿拉善盟| 修武县| 贵州省| 如东县| 安徽省| 随州市| 南陵县| 砀山县| 左权县| 华阴市|