本文詳細(xì)羅列歸納了Python常見數(shù)據(jù)結(jié)構(gòu),并附以實(shí)例加以說(shuō)明,相信對(duì)讀者有一定的參考借鑒價(jià)值。
總體而言Python中常見的數(shù)據(jù)結(jié)構(gòu)可以統(tǒng)稱為容器(container)。而序列(如列表和元組)、映射(如字典)以及集合(set)是三類主要的容器。
一、序列(列表、元組和字符串)
序列中的每個(gè)元素都有自己的編號(hào)。Python中有6種內(nèi)建的序列。其中列表和元組是最常見的類型。其他包括字符串、Unicode字符串、buffer對(duì)象和xrange對(duì)象。下面重點(diǎn)介紹下列表、元組和字符串。
1、列表
列表是可變的,這是它區(qū)別于字符串和元組的最重要的特點(diǎn),一句話概括即:列表可以修改,而字符串和元組不能。
(1)、創(chuàng)建
通過(guò)下面的方式即可創(chuàng)建一個(gè)列表:
list1=['hello','world']print list1list2=[1,2,3]print list2
輸出:
['hello', 'world'][1, 2, 3]
可以看到,這中創(chuàng)建方式非常類似于javascript中的數(shù)組。
(2)、list函數(shù)
通過(guò)list函數(shù)(其實(shí)list是一種類型而不是函數(shù))對(duì)字符串創(chuàng)建列表非常有效:
list3=list("hello")print list3輸出:
['h', 'e', 'l', 'l', 'o']
2、元組
元組與列表一樣,也是一種序列,唯一不同的是元組不能被修改(字符串其實(shí)也有這種特點(diǎn))。
(1)、創(chuàng)建
t1=1,2,3t2="jeffreyzhao","cnblogs"t3=(1,2,3,4)t4=()t5=(1,)print t1,t2,t3,t4,t5
輸出:
(1, 2, 3) ('jeffreyzhao', 'cnblogs') (1, 2, 3, 4) () (1,)從上面我們可以分析得出:
a、逗號(hào)分隔一些值,元組自動(dòng)創(chuàng)建完成;
b、元組大部分時(shí)候是通過(guò)圓括號(hào)括起來(lái)的;
c、空元組可以用沒(méi)有包含內(nèi)容的圓括號(hào)來(lái)表示;
d、只含一個(gè)值的元組,必須加個(gè)逗號(hào)(,);
(2)、tuple函數(shù)
tuple函數(shù)和序列的list函數(shù)幾乎一樣:以一個(gè)序列(注意是序列)作為參數(shù)并把它轉(zhuǎn)換為元組。如果參數(shù)就算元組,那么該參數(shù)就會(huì)原樣返回:
t1=tuple([1,2,3])t2=tuple("jeff")t3=tuple((1,2,3))print t1print t2print t3t4=tuple(123)print t45輸出:
(1, 2, 3)('j', 'e', 'f', 'f')(1, 2, 3)Traceback (most recent call last):
File "F:/Python/test.py", line 7, in <module>
t4=tuple(123)
TypeError: 'int' object is not iterable
3、字符串
(1)創(chuàng)建
str1='Hello world'print str1print str1[0]for c in str1: print c
輸出:
Hello worldHHello world
(2)格式化
字符串格式化使用字符串格式化操作符即百分號(hào)%來(lái)實(shí)現(xiàn)。
str1='Hello,%s' % 'world.'print str1
格式化操作符的右操作數(shù)可以是任何東西,如果是元組或者映射類型(如字典),那么字符串格式化將會(huì)有所不同。
strs=('Hello','world') #元組str1='%s,%s' % strsprint str1d={'h':'Hello','w':'World'} #字典str1='%(h)s,%(w)s' % dprint str1輸出:
Hello,worldHello,World
注意:如果需要轉(zhuǎn)換的元組作為轉(zhuǎn)換表達(dá)式的一部分存在,那么必須將它用圓括號(hào)括起來(lái):
str1='%s,%s' % 'Hello','world'print str1
輸出:
Traceback (most recent call last): File "F:/Python/test.py", line 2, in <module> str1='%s,%s' % 'Hello','world'TypeError: not enough arguments for format string
如果需要輸出%這個(gè)特殊字符,毫無(wú)疑問(wèn),我們會(huì)想到轉(zhuǎn)義,但是Python中正確的處理方式如下:
str1='%s%%' % 100print str1
輸出:
100%
對(duì)數(shù)字進(jìn)行格式化處理,通常需要控制輸出的寬度和精度:
from math import pistr1='%.2f' % pi #精度2print str1str1='%10f' % pi #字段寬10print str1str1='%10.2f' % pi #字段寬10,精度2print str1
輸出:
3.14 3.141593 3.14
字符串格式化還包含很多其他豐富的轉(zhuǎn)換類型,可參考官方文檔。
Python中在string模塊還提供另外一種格式化值的方法:模板字符串。它的工作方式類似于很多UNIX Shell里的變量替換,如下所示:
from string import Templatestr1=Template('$x,$y!')str1=str1.substitute(x='Hello',y='world')print str1輸出:
Hello,world!
如果替換字段是單詞的一部分,那么參數(shù)名稱就必須用括號(hào)括起來(lái),從而準(zhǔn)確指明結(jié)尾:
from string import Templatestr1=Template('Hello,w${x}d!')str1=str1.substitute(x='orl')print str1輸出:
Hello,world!
如要輸出$符,可以使用$$輸出:
from string import Templatestr1=Template('$x$$')str1=str1.substitute(x='100')print str1輸出:
100$
除了關(guān)鍵字參數(shù)之外,模板字符串還可以使用字典變量提供鍵值對(duì)進(jìn)行格式化:
from string import Templated={'h':'Hello','w':'world'}str1=Template('$h,$w!')str1=str1.substitute(d)print str1輸出:
Hello,world!
除了格式化之外,Python字符串還內(nèi)置了很多實(shí)用方法,可參考官方文檔,這里不再列舉。
4、通用序列操作(方法)
從列表、元組以及字符串可以“抽象”出序列的一些公共通用方法(不是你想像中的CRUD),這些操作包括:索引(indexing)、分片(sliceing)、加(adding)、乘(multiplying)以及檢查某個(gè)元素是否屬于序列的成員。除此之外,還有計(jì)算序列長(zhǎng)度、最大最小元素等內(nèi)置函數(shù)。
(1)索引
str1='Hello'nums=[1,2,3,4]t1=(123,234,345)print str1[0]print nums[1]print t1[2]
輸出
H2345
索引從0(從左向右)開始,所有序列可通過(guò)這種方式進(jìn)行索引。神奇的是,索引可以從最后一個(gè)位置(從右向左)開始,編號(hào)是-1:
str1='Hello'nums=[1,2,3,4]t1=(123,234,345)print str1[-1]print nums[-2]print t1[-3]
輸出:
o3123
(2)分片
分片操作用來(lái)訪問(wèn)一定范圍內(nèi)的元素。分片通過(guò)冒號(hào)相隔的兩個(gè)索引來(lái)實(shí)現(xiàn):
nums=range(10)print numsprint nums[1:5]print nums[6:10]print nums[1:]print nums[-3:-1]print nums[-3:] #包括序列結(jié)尾的元素,置空最后一個(gè)索引print nums[:] #復(fù)制整個(gè)序列
輸出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][1, 2, 3, 4][6, 7, 8, 9][1, 2, 3, 4, 5, 6, 7, 8, 9][7, 8][7, 8, 9]
不同的步長(zhǎng),有不同的輸出:
nums=range(10)print numsprint nums[0:10] #默認(rèn)步長(zhǎng)為1 等價(jià)于nums[1:5:1]print nums[0:10:2] #步長(zhǎng)為2print nums[0:10:3] #步長(zhǎng)為3 ##print nums[0:10:0] #步長(zhǎng)為0print nums[0:10:-2] #步長(zhǎng)為-2
輸出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 2, 4, 6, 8][0, 3, 6, 9][]
(3)序列相加
str1='Hello'str2=' world'print str1+str2num1=[1,2,3]num2=[2,3,4]print num1+num2print str1+num1
輸出:
Hello world[1, 2, 3, 2, 3, 4]
Traceback (most recent call last):
File "F:/Python/test.py", line 7, in <module>
print str1+num1
TypeError: cannot concatenate 'str' and 'list' objects
(4)乘法
print [None]*10str1='Hello'print str1*2num1=[1,2]print num1*2print str1*num1
輸出:
[None, None, None, None, None, None, None, None, None, None]HelloHello[1, 2, 1, 2]
Traceback (most recent call last):
File "F:/Python/test.py", line 5, in <module>
print str1*num1
TypeError: can't multiply sequence by non-int of type 'list'
(5)成員資格
in運(yùn)算符會(huì)用來(lái)檢查一個(gè)對(duì)象是否為某個(gè)序列(或者其他類型)的成員(即元素):
str1='Hello'print 'h' in str1 print 'H' in str1num1=[1,2]print 1 in num1
輸出:
FalseTrueTrue
(6)長(zhǎng)度、最大最小值
通過(guò)內(nèi)建函數(shù)len、max和min可以返回序列中所包含元素的數(shù)量、最大和最小元素。
str1='Hello'print len(str1) print max(str1)print min(str1)num1=[1,2,1,4,123]print len(num1) print max(num1)print min(num1)
輸出:
5oH51231
二、映射(字典)
映射中的每個(gè)元素都有一個(gè)名字,如你所知,這個(gè)名字專業(yè)的名稱叫鍵。字典(也叫散列表)是Python中唯一內(nèi)建的映射類型。
1、鍵類型
字典的鍵可以是數(shù)字、字符串或者是元組,鍵必須唯一。在Python中,數(shù)字、字符串和元組都被設(shè)計(jì)成不可變類型,而常見的列表以及集合(set)都是可變的,所以列表和集合不能作為字典的鍵。鍵可以為任何不可變類型,這正是Python中的字典最強(qiáng)大的地方。
list1=["hello,world"]set1=set([123])d={}d[1]=1print dd[list1]="Hello world."d[set1]=123print d輸出:
{1: 1}Traceback (most recent call last):
File "F:/Python/test.py", line 6, in <module>
d[list1]="Hello world."
TypeError: unhashable type: 'list'
2、自動(dòng)添加
即使鍵在字典中并不存在,也可以為它分配一個(gè)值,這樣字典就會(huì)建立新的項(xiàng)。
3、成員資格
表達(dá)式item in d(d為字典)查找的是鍵(containskey),而不是值(containsvalue)。
Python字典強(qiáng)大之處還包括內(nèi)置了很多常用操作方法,可參考官方文檔,這里不再列舉。
思考:根據(jù)我們使用強(qiáng)類型語(yǔ)言的經(jīng)驗(yàn),比如C#和Java,我們肯定會(huì)問(wèn)Python中的字典是線程安全的嗎?
三、集合
集合(Set)在Python 2.3引入,通常使用較新版Python可直接創(chuàng)建,如下所示:
strs=set(['jeff','wong','cnblogs'])nums=set(range(10))
看上去,集合就是由序列(或者其他可迭代的對(duì)象)構(gòu)建的。集合的幾個(gè)重要特點(diǎn)和方法如下:
1、副本是被忽略的
集合主要用于檢查成員資格,因此副本是被忽略的,如下示例所示,輸出的集合內(nèi)容是一樣的。
set1=set([0,1,2,3,0,1,2,3,4,5])print set1 set2=set([0,1,2,3,4,5])print set2
輸出如下:
set([0, 1, 2, 3, 4, 5])set([0, 1, 2, 3, 4, 5])
2、集合元素的順序是隨意的
這一點(diǎn)和字典非常像,可以簡(jiǎn)單理解集合為沒(méi)有value的字典。
strs=set(['jeff','wong','cnblogs'])print strs
輸出如下:
set(['wong', 'cnblogs', 'jeff'])
3、集合常用方法
a、交集union
set1=set([1,2,3])set2=set([2,3,4])set3=set1.union(set2)print set1print set2print set3
輸出:
set([1, 2, 3])set([2, 3, 4])set([1, 2, 3, 4])
union操作返回兩個(gè)集合的并集,不改變?cè)屑稀J褂冒次慌c(OR)運(yùn)算符“|”可以得到一樣的結(jié)果:
set1=set([1,2,3])set2=set([2,3,4])set3=set1|set2print set1print set2print set3
輸出和上面union操作一模一樣的結(jié)果。
其他常見操作包括&(交集),<=,>=,-,copy()等等,這里不再列舉。
set1=set([1,2,3])set2=set([2,3,4])set3=set1&set2print set1print set2print set3print set3.issubset(set1)set4=set1.copy()print set4print set4 is set1
輸出如下:
set([1, 2, 3])set([2, 3, 4])set([2, 3])Trueset([1, 2, 3])False
b、add和remove
和序列添加和移除的方法非常類似,可參考官方文檔:
set1=set([1])print set1set1.add(2)print set1set1.remove(2)print set1print set1print 29 in set1set1.remove(29) #移除不存在的項(xiàng)
輸出:
set([1])set([1, 2])set([1])set([1])False
Traceback (most recent call last):
File "F:/Python/test.py", line 9, in <module>
set1.remove(29) #移除不存在的項(xiàng)
KeyError: 29
4、frozenset
集合是可變的,所以不能用做字典的鍵。集合本身只能包含不可變值,所以也就不能包含其他集合:
set1=set([1])set2=set([2])set1.add(set2)
輸出如下:
Traceback (most recent call last):
File "F:/Python/test.py", line 3, in <module>
set1.add(set2)
TypeError: unhashable type: 'set'
可以使用frozenset類型用于代表不可變(可散列)的集合:
set1=set([1])set2=set([2])set1.add(frozenset(set2))print set1
輸出:
set([1, frozenset([2])])
新聞熱點(diǎn)
疑難解答
圖片精選