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

首頁 > 編程 > Python > 正文

Python中3種內建數據結構:列表、元組和字典

2020-02-23 06:15:37
字體:
來源:轉載
供稿:網友

Python中有3種內建的數據結構:列表、元組和字典。參考簡明Python教程


1. 列表
list是處理一組有序項目的數據結構,即你可以在一個列表中存儲一個 序列 的項目。假想你有一個購物列表,上面記載著你要買的東西,你就容易理解列表了。只不過在你的購物表上,可能每樣東西都獨自占有一行,而在Python中,你在每個項目之間用逗號分割。

列表中的項目應該包括在方括號中,這樣Python就知道你是在指明一個列表。一旦你創建了一個列表,你可以添加、刪除或是搜索列表中的項目。由于你可以增加或刪除項目,我們說列表是 可變的 數據類型,即這種類型是可以被改變的。
例:

#!/usr/bin/env python#coding:utf8 list = ['Linux', 'Nginx', 'MySQL', 'PHP'] print 'These items are:',for item in list:print item, print '/nadd Apache.'list.append('Apache')print 'list is now', list print '/nI will sort my list now'list.sort()print 'Sorted list is %s' % list print '/nThe first item ', list[0]item0 = list[0]print 'delete first item'del list[0]print 'list is now', list

輸出

$python using_list.pyThese items are: Linux Nginx MySQL PHPadd Apache.list is now ['Linux', 'Nginx', 'MySQL', 'PHP', 'Apache'] I will sort my list nowSorted list is ['Apache', 'Linux', 'MySQL', 'Nginx', 'PHP'] The first item Apachedelete first itemlist is now ['Linux', 'MySQL', 'Nginx', 'PHP']

2. 元組
元組和列表十分類似,只不過元組和字符串一樣是 不可變的 即你不能修改元組。元組通過圓括號中用逗號分割的項目定義。元組通常用在使語句或用戶定義的函數能夠安全地采用一組值的時候,即被使用的元組的值不會改變。
例:

#!/usr/bin/env python#coding:utf8 zoo = ('wolf', 'elephant', 'penguin')print 'Number of animals in the zoo is', len(zoo) new_zoo = ('monkey', 'dolphin', zoo)print 'Number of animals in the new zoo is', len(new_zoo)print 'All animals in new zoo are', new_zooprint 'Animals brought from old zoo are', new_zoo[2]print 'Last animal brought from old zoo is', new_zoo[2][2]

輸出

$ python using_tuple.pyNumber of animals in the zoo is 3Number of animals in the new zoo is 3All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))Animals brought from old zoo are ('wolf', 'elephant', 'penguin')Last animal brought from old zoo is penguin

3. 字典
字典類似于你通過聯系人名字查找地址和聯系人詳細情況的地址簿,即,我們把鍵(名字)和值(詳細情況)聯系在一起。注意,鍵必須是唯一的,就像如果有兩個人恰巧同名的話,你無法找到正確的信息。

注意,你只能使用不可變的對象(比如字符串)來作為字典的鍵,但是你可以不可變或可變的對象作為字典的值。基本說來就是,你應該只使用簡單的對象作為鍵。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 闽侯县| 腾冲县| 广东省| 鄂伦春自治旗| 太仓市| 德安县| 碌曲县| 晴隆县| 阿坝| 晋中市| 镇宁| 达孜县| 宜城市| 谢通门县| 故城县| 庆城县| 滦南县| 蓝山县| 五原县| 堆龙德庆县| 东兰县| 健康| 湖北省| 晋宁县| 黄大仙区| 宜城市| 电白县| 临沂市| 巴中市| 茌平县| 抚顺县| 大石桥市| 卓资县| 威宁| 靖西县| 罗山县| 竹山县| 东兰县| 巴东县| 房山区| 冀州市|