Python学习笔记3(数据结构)

时间:2023-03-09 01:33:40
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]的相关操作