python的基礎數據結構有:列表(list),元祖(tuple),字典(dict),字符串(string),集合(set),下面分別進行介紹:
1、創建
list = ['1',(1,2),'1', '2']
>>> print len(list)
4
>>> del list[0]
>>> print list
[(1, 2), '1', '2']
>>> del list[0:2]
>>> print list
['2']
4、添加
>>> list.append('3')
>>> print list
['2', '3']
5、插入
>>> list[0:0] = ['sample value']
>>> print list
['sample value', '2', '3']
>>> list[0:0] = ['sample value', 'sample value 1']
>>> print list
['sample value', 'sample value 1', 'sample value', '2', '3']
>>> list[1:2] = ['sample value 2', 'sample value 3']
>>> print list
['sample value', 'sample value 2', 'sample value 3', 'sample value', '2', '3']
6、取值,遍歷
取值單個值
>>> print list[0]
sample value
>>> print list[1]
sample value 2
>>> print list[2]
sample value 3
取片段
>>> print list[2:4]
['sample value 3', 'sample value']
遍歷
>>> for line in list:
... print line
...
sample value
sample value 2
sample value 3
sample value
2
3
7、list的方法
L.append(var) #追加元素
L.insert(index,var)
L.pop(var) #返回最後一個元素,並從list中刪除之
L.remove(var) #刪除第一次出現的該元素
L.count(var) #該元素在列表中出現的個數
L.index(var) #該元素的位置,無則拋異常
L.extend(list) #追加list,即合併list到L上
L.sort() #排序
L.reverse() #倒序
二、元祖(tuple)
#元組和列表十分類似,只不過元組和字符串一樣是
#不可變的 即你不能修改元組
tuple = ('a', 'b', 'c', 'd', 'e')
>>> print tuple[0]
a
>>> print tuple[0:2]
('a', 'b')
三、字符串(string)
1、string = "Hello My friend">>> print string[0]
H
>>> print string[0:5]
Hello
2、字符串包含判斷操作符:in,not in
>>> print 'He' in string
True
>>> print 'sHe' in string
False
3、*後面跟數字表示字符串重複的次數,比如
print 'hello'*5
>>> hellohellohellohellohello
4、處理字符串的內置函數
len(str) #串長度
cmp("my friend", str) #字符串比較。第一個大,返回1
max('abcxyz') #尋找字符串中最大的字符
min('abcxyz') #尋找字符串中最小的字符
5、string的轉換
float(str) #變成浮點數,float("1e-1") 結果爲0.1
int(str) #變成整型, int("12") 結果爲12
int(str,base) #變成base進制整型數,int("11",2) 結果爲2
long(str) #變成長整型,
long(str,base) #變成base進制長整型,
6、字符串的格式化(注意其轉義字符,大多如C語言的,略)
str_format % (參數列表) #參數列表是以tuple的形式定義的,即不可運行中改變
>>>print ""%s's height is %dcm" % ("My brother", 180)
#結果顯示爲 My brother's height is 180cm
7、string模塊,還提供了很多方法,如
S.find(substring, [start [,end]]) #可指範圍查找子串,返回索引值,否則返回-1
S.rfind(substring,[start [,end]]) #反向查找
S.index(substring,[start [,end]]) #同find,只是找不到產生ValueError異常
S.rindex(substring,[start [,end]])#同上反向查找
S.count(substring,[start [,end]]) #返回找到子串的個數
S.lowercase()
S.capitalize() #首字母大寫
S.lower() #轉小寫
S.upper() #轉大寫
S.swapcase() #大小寫互換
S.split(str, ' ') #將string轉list,以空格切分
S.join(list, ' ') #將list轉string,以空格連接
四、字典(dict)
key-value的數據結構,跟c++中的stl:map類似。1、創建字典:
(1)基本
d = {} #空字典
d = {'name':'tom', 'age':22}
#等價
d = {}
d['name'] = 'tom'
d['age'] = 22
(2)dict
d = dict() #空
d = dict(name='tom', age=22)
d = dict([('name','tom'), ('age',22)])
#等價
keys = ['name','age']
values = ['tom', 22]
d = dict(zip(keys,values))
(3) fromkeys
>>> dict.fromkeys(['name','age'],'default_value')
{'age': 'default_value', 'name': 'default_value'}
2、判斷key是否存在
if k in d: #k not in
dosomething()
3、讀取
print d['name'] #存在得到結果,但是若鍵不存在,將引發異常KeyError。慎用,建議不使用
print d.get('name', 'jack') #存在得到,若鍵不存在,返回第二個參數default_value.若是沒有設default_value返回None
#使用用例
if k in d:
print d[k]
try:
print d[k]
except KeyError:
dosomething()
print d.get(k, default)
#等價 d[k] if k in d else default
4、遍歷
for key in d:
print key, d[key]
#等價 for key in d.keys()
for key,value in d.items():
print key, value
5、修改
d['name'] = 'tom'
d.update({'name':'tom'}) #這裏支持一整組值
d.update( [ ('name','tom'), ('age',2) ] ) #每個元組兩個元素,(key,value)
d.update('name'='tom', 'age'=4)
6、刪除
del d['key']
value = d.pop('key') #刪除並返回值
d.clear() #清空
7、排序
d = {'a':10, 'c':8, 'b':9, 'd':7}
(1)字典排序 按照key排序
keys = d.keys()
keys.sort()
for key in keys:
print d.get(key)
結果爲:
10
9
8
7
(2)按照value進行排序
sorted(d.items(), lambda x,y: cmp(x[1],y[1]))
結果爲:
[('d', 7), ('c', 8), ('b', 9), ('a', 10)]
(3)另一種排序方法
sorted(d)
>>> print d
{'a': 10, 'c': 8, 'b': 9, 'd': 7}
8、其他dictionary的方法
D.get(key, 0) #同dict[key],多了個沒有則返回缺省值,0。[]沒有則拋異常
D.has_key(key) #有該鍵返回TRUE,否則FALSE
D.keys() #返回字典鍵的列表
D.values() #以列表的形式返回字典中的值,返回值的列表中可包含重複元素
D.items() #將所有的字典項以列表方式返回,這些列表中的每一項都來自於(鍵,值),但是項在返回時並沒有特殊的順序
D.update(dict2) #增加合併字典
D.popitem() #得到一個pair,並從字典中刪除它。已空則拋異常
D.clear() #清空字典,同del dict
D.copy() #拷貝字典
D.cmp(dict1,dict2) #比較字典,(優先級爲元素個數、鍵大小、鍵值大小)
#第一個大返回1,小返回-1,一樣返回0
dictionary的複製
dict1 = dict #別名
dict2=dict.copy() #克隆,即另一個拷貝。
五、集合(set)
python 的集合類型和 其他語言類似, 是一個無序不重複元素集, 基本功能包括關係測試和消除重複元素.集合對象還支持union(聯合), intersection(交), difference(差)和sysmmetricdifference(對稱差集)等數學運算,和我們初中數學學的集合的非常的相似。1、創建
a = [2,3,4,2,1]
seta = set(a)
>>> print seta
set([1, 2, 3, 4]) #重複的2被刪除掉了
setb = set('abracadabra')
setc = set('alacazam')
>>> print setc
set(['a', 'c', 'z', 'm', 'l'])
2、操作
#1)in or not in
x in seta
x not in seta
3、測試集合是否完全包含
s.issubset(t) #測試是否 s 中的每一個元素都在 t 中
s <= t
s.issuperset(t) #測試是否 t 中的每一個元素都在 s 中
s >= t
4、其他運算符
s.union(t) # 合併
s | t
s.intersection(t) #求交
s & t
s.difference(t) #返回一個新的 set 包含 s 中有但是 t 中沒有的元素
s - t
s.symmetric_difference(t) # 返回一個新的 set 包含 s 和 t 中不重複的元素
s ^ t
s.copy() # 返回 set “s”的一個淺複製
s.update(t)
s |= t
s.intersection_update(t)
s &= t
s.difference_update(t)
s -= t
s.symmetric_difference_update(t)
s ^= t
s.add(x) #向 set “s”中增加元素 x
s.remove(x) #從 set “s”中刪除元素 x, 如果不存在則引發 KeyError
s.discard(x) #如果在 set “s”中存在元素 x, 則刪除
s.pop() #刪除並且返回 set “s”中的一個不確定的元素, 如果爲空則引發 KeyError
s.clear() #刪除 set “s”中的所有元素
原文鏈接:http://www.xuebuyuan.com/2022639.html
作者:mitac