Python學習筆記3(數據結構)


1.元組結構(Tuple)

元組由不同的元素組成,每個元素可以存儲不同類型的數據,如字符串、數字甚至元組。元組創建后不能修改。

元組通常代表一行數據,而元組中的元素代表不同的數據項。

1.1元組的創建

創建時可不指定元素的個數,相當於不定長的數組,但一旦創建就不能修改元組的長度。

tuple = (元素1, 元素2, ...)

#創建並初始化 tuple = ("apple", "banana","grape", "orange" ) #創建一個空的元組 tuple = ()

創建只包含一個變量的元組時,單元素后面的逗號不能省略。因為Python無法區分變量tuple是元組還是表達式。

1.2元組的訪問

tuple[n]                             #訪問第n+1個元素

元組訪問的特殊用法:

  • 負數索引

        從元組的尾部開始技術,最尾端的元素索引表示“-1”,次尾端表示“-2”,以此類推。

  • 分片索引

        分片是元組的一個子集,分片是從第1個索引到第2個索引(包含第2個索引所指向的元素)所指定的所有元素。分片索引可以為正數或者負數,兩個索引之間用冒號分隔。分片的格式如下:

tuple[m:n]                             # m、n可以是0、正整數或負整數
#   表示tuple中第m+1個元素到第n個元素,不包括n+1

python稱創建元組的過程為“打包”,相反,元組也可以執行解包的操作。

#  打包
tuple = ("apple", "banana","grape", "orange" )

# 解包
a, b, c, d = tuple
print (a, b, c, d)                 #結果為 apple banana grape orange

1.3元組的遍歷

# 二元元組的遍歷
tuple = ( ("apple", "banana"), ("grape", "orange"), ("melon",), ("charry",) )

for i in range( len(tuple) ):
    print ("tuple[%d] : "  % i , " " ,)
    for j in range( len(tuple[i]) ):
        print (tuple[i][j], " ",)
    print()


#output
tuple[0] : apple banana
tuple[1] : grape orange
tuple[2] : melon
tuple[3] : charry
tuple = ( ("apple", "banana"), ("grape", "orange"), ("melon",), ("charry",) )
for i in tuple:
    for j in i:
        print(j)            

 #output
apple banana grape orange melon charry

 2.列表結構

2.1列表基本操作

通常作為函數的返回類型。和元組類似,也是由一組元素組成的,列表可以實現添加、刪除和查找操作,元素的值可以被修改。

# 列表操作

# 定義列表
list = [ "apple", "banana", "grape", "orange"]
print (list)
print (list[2])

# 在列表末尾添加元素
list.append("melon")
# 向列表list[1]處插入元素
list.insert(1, "charry")
print (list)

# 從列表中移除grape
list.remove("grape")
print (list)
# 打印列表最后一個元素
print ( list.pop() )

 2.2列表的使用

列表與元組相似,同樣支持負數索引、分片以及多元列表等特性。

# 負數索引和分片的使用
list = [ "apple", "banana", "grape", "orange"]
print (list[-2])                            # grape
print (list[1:3])                          # ['banana', 'grape']
print (list[-3:-1])                       # ['banana', 'grape']

# 二元列表的遍歷
list = [ ["apple", "banana"], ["grape", "orange"], ["melon"], ["charry"] ]
for i in range( len(list) ):
    print ( "list[%d] :" % i, " ",)
    for j in range( len(list[i]) ):
        print (list[i][j], " ",)
    print()

列表的連接可以使用extend(),或使用運算符“+”或“+=”。

list1 = ["apple", "banana"]
list2 = ["grape", "orange"]
# 將list2接在list1后
list1.extend(list2)
print (list1)

list3 = ["melon"]
list1 = list1 + list3
print (list1)

list +=  ["charry"] ]
print (list1)

list1 = ["apple", "banana"] * 2
print (list1)

2.3列表的查找、排序、反轉

list = [ "apple", "banana", "grape", "orange"]
# 打印grape的索引
print ( list.index("grape") )
# 判斷orange是否在列表中
print ( "orange" in list )
list = ["banana", "apple",  "orange", "grape"]
# 按字典序排序
list.sort()
print ("Sorted list: ", list)
# 反轉
list.reverse()
print ("Reversed list: ", list)

2.4列表實現堆棧和隊列

# 堆棧的實現
list = ["apple",  "grape", "grape"]
list.append("orange")
print (list)
print ("彈出的元素: ", list.pop())
print (list)

 

 # 隊列的實現

list = ["apple",  "grape", "grape"]
list.append("orange")
print (list)
print ("彈出的元素: ", list.pop(0))
print (list)

3.字典結構
字典是由“鍵-值”對組成的集合,字典中的“值”通過“鍵”來引用。

3.1字典的創建

# 字典創建格式
dictionary = {key1 : value1, key2 : value2, ...}

# 空字典
dictionary = {}

# 字典的創建和訪問
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print (dict)                # {'a' : 'apple', 'b' : 'banana', 'g' : 'grape', 'o' : 'orange'}
print (dict["a"])         # apple

print ("%s, %(a)s, %(b)s % {"a": "apple", "b": "banana"})
# 輸出:  {'a' : 'apple', 'b' : 'banana'}, apple, banana

3.2字典的訪問

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"} #添加 dict["m"] = "melon" # 刪除 del(dict["a"]) # 修改 dict["a"] = "almond" # 彈出字典中鍵位b的元素 print (dict.pop("b") print (dict) # 清空dict dict.clear() print (dict) 
# 字典的遍歷
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
    print ("dict[%s] = " % k, dict[k])

# output
dict[a] = apple
dict[b] = banana
dict[g] = grape
dict[o] = orange
# 字典item()的使用
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print (dict.items())

# output
 {('a' , 'apple'), ('b' , 'banana'), ('g' , 'grape'), ('o' , 'orange')}

# 調用item()實現字典的遍歷
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k,v) in dict.items():
    print ("dict[%s] ="  % k, v)

# output
dict[a] = apple
dict[b] = banana dict[g] = grape
dict[o] = orange

元組、列表、字典作為字典的value值時,該字典稱為混合型字典。

# 混合型字典的創建格式
dict = {"key1" : (tuple), "key2" : [list], "key3" : [dictionary], ...}

# 訪問方法由外向內疊加

3.3字典的方法

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
# keys()返回字典的key列表
print (dict.keys() )        #  {'a', 'b', 'g', 'o'}

# values()返回字典的value列表
print ( dict.values() )     # {'apple', 'banana', 'grape', 'orange'}

另一個獲取value的辦法是使用字典的get(),get()聲明如下:

D.get(k[,d])  ->  D[k]      
# k為鍵值,d可作為get返回值,默認值為None
# k在字典D中,返回D[K];若不在,返回參數d

#get等價語句如下
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
    print (D["key1"])
else:
    print ("None")

# 用例
print (dict.get("o", "apple") )   #輸出鍵值o的值,若不存在輸出apple

若要添加新元素到已存在的字典中,調用update()函數。update把一個字典的key和value全復制到另一個字典中,相當於一個合並函數。

# updat()等價語句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print (D)                # {'key3' : 'value3', 'key2' : 'value2', 'key1' : 'value1', 'key4' : 'value4'}

# 字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
    D[k] = E[k]
print (D)                # {'key2' : 'value3', 'key1' : 'value1', 'key4' : 'value4'}

 

# 字典的更新
dict = {"a" : "apple", "b" : "banana"}
dict2 = {"g" : "grape", "o" : "orange"}
dict.update(dict2)
print (dict)             #{'a' : 'apple', 'g' : 'grape', 'b' : 'banana', 'o' : 'orange'}

字典的setdefault()可以創建新的元素並設置默認值

# 聲明
D.setdefault(k[,d])  -> D.get(k,d)
若k在字典中,返回get(k,d)的結果;若不在,添加新元素D[k]並調用get(k,d)返回d的值

# 設置默認值
dict = {}
dict.setdefault("a")
print (dict)                 # {'a': None}
dict["a"] = "apple"
dict.setdefault("a","None")
print (dict)                 # {'a': 'apple'}

 3.4字典的排序、復制

# 調用sorted()排序
dict = {"a" : "apple", "o" : "orange", "b" : "grape", "g" : "banana"}
print (dict)

# 按照key排序
print ( sorted(dict.item(), key = lambda d: d[0]) )
# 按照value排序
print ( sorted(dict.item(), key = lambda d: d[1]) )

# lambda可用於創建匿名函數,用於返回一些計算結果。

若將字典A的內容復制到B並清除B,可以使用copy()

#copy()定義
D.copy() -> a shallow copy of D

# 字典的淺拷貝
dict = {"a" : "apple", "b" : "banana"}
dict2 = {"g" : "grape", "o" : "orange"}
dict2 = dict.copy()
print (dict2)

深拷貝能夠拷貝對象內部所有的數據和引用,引用相當於C語言中指針的概念,Python並不存在指針,但是變量的內存結構通過引用來維護變量。而淺拷貝只是復制數據,並沒有復制數據的引用,新的數據和舊的數據使用同一塊內存空間。

eg.B淺拷貝A的數據,B改變,A也改變。

deepcopy()用於深拷貝.

# 字典的深拷貝
import copy
dict = {"a" : "apple", "b" :{"g" : "grape", "o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy(dict)
dict2["b"]["g"] = "orange"
print (dict)                                # 不改變
dict3["b"]["g"] = "orange"
print (dict)                                # 改變

 3.5全局字典——sys.modules模塊

sys.modules是一個全局函數,這個字典是Python啟動后就加載在內存中的。每當程序員導入新的模板,sys.modules都將記錄這些模板。字典sys.modules對加載模板起到了緩存的作用。當模板第一次導入,sys.modules自動記錄。第二次導入時,Python直接在字典中查找。

import sys
print ( sys.modules.keys() )           #  keys()返回當前環境下加載的模塊
print ( sys.modules.values() )        #  values()返回這些模板引用路徑
print ( sys.modules["os"] )            #  返回索引"os"對應的引用
# 導入模塊的過濾 import sys d = sys.modules.copy() # 把當前導入的模塊信息保存到字典d中 import copy, string # 導入模塊copy、string,此時sys.modules包含原有模塊和新導入的模塊 print ( zip( set(sys.modules) - set(d) ) ) # 使用zip進行modules過濾 # set()把字典sys.modules、字典d存入set集合中,set集合實現了減法運算符 # set(sys.modules) - set(d)返回字典d中沒有、而字典sys.modules中存在的模塊 # 然后用zip()對set集合“解包”,返回一個列表。該列表就是import copy,string語句導入的模塊 # output: [('copy',), ('strop',), ('string',)] 

 4.序列

是具有索引和切片能力的集合。元組、列表和字符串具有通過索引訪問某個具體的值,或通過切片返回一段切片的能力,因此元組、列表和字符串都屬於序列。

 

PS:  Python中的X[:,0]和X[:,0:1]的相關操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM