99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python中內(nèi)置數(shù)據(jù)類型list,tuple,dict,set的區(qū)別和用法
Python中內(nèi)置數(shù)據(jù)類型list,tuple,dict,set的區(qū)別和用法
2018-02-05
收藏

Python中內(nèi)置數(shù)據(jù)類型list,tuple,dict,set的區(qū)別和用法

Python語言簡潔明了,可以用較少的代碼實現(xiàn)同樣的功能。這其中Python的四個內(nèi)置數(shù)據(jù)類型功不可沒,他們即是list, tuple, dict, set。這里對他們進行一個簡明的總結(jié)。

List
字面意思就是一個集合,在Python中List中的元素用中括號[]來表示,可以這樣定義一個List:    
L = [12, 'China', 19.998]

可以看到并不要求元素的類型都是一樣的。當然也可以定義一個空的List:
    
L = []

Python中的List是有序的,所以要訪問List的話顯然要通過序號來訪問,就像是數(shù)組的下標一樣,一樣是下標從0開始:    
>>> print L[0]
12
千萬不要越界,否則會報錯    
>>> print L[3]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list index out of range

List也可以倒序訪問,通過“倒數(shù)第x個”這樣的下標來表示序號,比如-1這個下標就表示倒數(shù)第一個元素:    
>>> L = [12, 'China', 19.998]
>>> print L[-1]
19.998

-4的話顯然就越界了    
>>> print L[-4]
 
Traceback (most recent call last):
 File "<pyshell#2>", line 1, in <module>
  print L[-4]
IndexError: list index out of range
>>>

List通過內(nèi)置的append()方法來添加到尾部,通過insert()方法添加到指定位置(下標從0開始):    
>>> L = [12, 'China', 19.998]
>>> L.append('Jack')
>>> print L
[12, 'China', 19.998, 'Jack']
>>> L.insert(1, 3.14)
>>> print L
[12, 3.14, 'China', 19.998, 'Jack']
>>>

通過pop()刪除最后尾部元素,也可以指定一參數(shù)刪除指定位置:
    
>>> L.pop()
'Jack'
>>> print L
[12, 3.14, 'China', 19.998]
>>> L.pop(0)
12
>>> print L
[3.14, 'China', 19.998]

也可以通過下標進行復制替換    
>>> L[1] = 'America'
>>> print L
[3.14, 'America', 19.998]

Tuple

Tuple可以看做是一種“不變”的List,訪問也是通過下標,用小括號()表示:    
>>> t = (3.14, 'China', 'Jason')
>>> print t
(3.14, 'China', 'Jason')

但是不能重新賦值替換:    
>>> t[1] = 'America'
 
Traceback (most recent call last):
 File "<pyshell#21>", line 1, in <module>
  t[1] = 'America'
TypeError: 'tuple' object does not support item assignment

也沒有pop和insert、append方法。

可以創(chuàng)建空元素的tuple:

t = ()
或者單元素tuple (比如加一個逗號防止和聲明一個整形歧義):

t = (3.14,)

那么tuple這個類型到底有什么用處呢?要知道如果你希望一個函數(shù)返回多個返回值,其實只要返回一個tuple就可以了,因為tuple里面的含有多個值,而且是不可變的(就像是java里面的final)。當然,tuple也是可變的,比如:    
>>> t = (3.14, 'China', 'Jason', ['A', 'B'])
>>> print t
(3.14, 'China', 'Jason', ['A', 'B'])
>>> L = t[3]
>>> L[0] = 122
>>> L[1] = 233
>>> print t
(3.14, 'China', 'Jason', [122, 233])

這是因為Tuple所謂的不可變指的是指向的位置不可變,因為本例子中第四個元素并不是基本類型,而是一個List類型,所以t指向的該List的位置是不變的,但是List本身的內(nèi)容是可以變化的,因為List本身在內(nèi)存中的分配并不是連續(xù)的。

Dict

Dict是Python中非常重要的數(shù)據(jù)類型,就像它的字面意思一樣,它是個活字典,其實就是Key-Value鍵值對,類似于HashMap,可以用花括號{}通過類似于定義一個C語言的結(jié)構(gòu)體那樣去定義它:    
>>> d = {
  'Adam': 95,
  'Lisa': 85,
  'Bart': 59,
  'Paul': 75
}
>>> print d
{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Bart': 59}

可以看到打印出來的結(jié)果都是Key:Value的格式,可以通過len函數(shù)計算它的長度(List,tuple也可以):

>>> len(d)
4

可以直接通過鍵值對方式添加dict中的元素:    
>>> print d
{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Bart': 59}
>>> d['Jone'] = 99
>>> print d
{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Jone': 99, 'Bart': 59}

List和Tuple用下標來訪問內(nèi)容,而Dict用Key來訪問: (字符串、整型、浮點型和元組tuple都可以作為dict的key)    
>>> print d['Adam']
95

如果Key不存在,會報錯:    
>>> print d['Jack']
 
Traceback (most recent call last):
 File "<pyshell#40>", line 1, in <module>
  print d['Jack']
KeyError: 'Jack'

所以訪問之前最好先查詢下key是否存在:    
>>> if 'Adam' in d : print 'exist key'
 
exist key

或者直接用保險的get方法:    
>>> print d.get('Adam')
95
>>> print d.get('Jason')
None

至于遍歷一個dict,實際上是在遍歷它的所有的Key的集合,然后用這個Key來獲得對應的Value:    
>>> for key in d : print key, ':', d.get(key)
 
Lisa : 85
Paul : 75
Adam : 95
Bart : 59

Dict具有一些特點:

查找速度快。無論是10個還是10萬個,速度都是一樣的,但是代價是耗費的內(nèi)存大。List相反,占用內(nèi)存小,但是查找速度慢。這就好比是數(shù)組和鏈表的區(qū)別,數(shù)組并不知道要開辟多少空間,所以往往開始就會開辟一個大空間,但是直接通過下標查找速度快;而鏈表占用的空間小,但是查找的時候必須順序的遍歷導致速度很慢
沒有順序。Dict是無順序的,而List是有序的集合,所以不能用Dict來存儲有序集合
Key不可變,Value可變。一旦一個鍵值對加入dict后,它對應的key就不能再變了,但是Value是可以變化的。所以List不可以當做Dict的Key,但是可以作為Value:    
>>> print d
{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Jone': 99, 'Bart': 59}
>>> d['NewList'] = [12, 23, 'Jack']
>>> print d
{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 99, 'Lisa': 85, 'Paul': 75}
Key不可重復。(下面例子中添加了一個'Jone':0,但是實際上原來已經(jīng)有'Jone'這個Key了,所以僅僅是改了原來的value)    
>>> print d
{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 99, 'Lisa': 85, 'Paul': 75}
>>> d['Jone'] = 0
>>> print d
{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 0, 'Lisa': 85, 'Paul': 75}

Dict的合并,如何將兩個Dict合并為一個,可以用dict函數(shù):    
>>> d1 = {'mike':12, 'jack':19}
>>> d2 = {'jone':22, 'ivy':17}
>>> dMerge = dict(d1.items() + d2.items())
>>> print dMerge
{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

或者    
>>> dMerge2 = dict(d1, **d2)
>>> print dMerge2
{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

方法2比方法1速度快很多,方法2等同于:    
>>> dMerge3 = dict(d1)
>>> dMerge3.update(d2)
>>> print dMerge
{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

set

set就像是把Dict中的key抽出來了一樣,類似于一個List,但是內(nèi)容又不能重復,通過調(diào)用set()方法創(chuàng)建:

>>> s = set(['A', 'B', 'C'])
就像dict是無序的一樣,set也是無序的,也不能包含重復的元素。

對于訪問一個set的意義就僅僅在于查看某個元素是否在這個集合里面:    
>>> print 'A' in s
True
>>> print 'D' in s
False

大小寫是敏感的。

也通過for來遍歷:    
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
#tuple
for x in s:
  print x[0],':',x[1]
 
>>>
Lisa : 85
Adam : 95
Bart : 59

通過add和remove來添加、刪除元素(保持不重復),添加元素時,用set的add()方法:    
>>> s = set([1, 2, 3])
>>> s.add(4)
>>> print s
set([1, 2, 3, 4])
如果添加的元素已經(jīng)存在于set中,add()不會報錯,但是不會加進去了:    
>>> s = set([1, 2, 3])
>>> s.add(3)
>>> print s
set([1, 2, 3])

刪除set中的元素時,用set的remove()方法:    
>>> s = set([1, 2, 3, 4])
>>> s.remove(4)
>>> print s
set([1, 2, 3])

如果刪除的元素不存在set中,remove()會報錯:    
>>> s = set([1, 2, 3])
>>> s.remove(4)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 4

所以如果我們要判斷一個元素是否在一些不同的條件內(nèi)符合,用set是最好的選擇,下面例子:    
months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',])
x1 = 'Feb'
x2 = 'Sun'
 
if x1 in months:
  print 'x1: ok'
else:
  print 'x1: error'
 
if x2 in months:
  print 'x2: ok'
else:
  print 'x2: error'
 
>>>
x1: ok
x2: error

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }