Python中的容器有四种:
List,Tuple,Set,Dictionary
List
语法:[ 123 , "456" , classObjectA , [123,"456"] ]
特征:中括号包裹,逗号隔开元素,元素类型任意,可以嵌套,可以用 index 进行读写
特点:最灵活,元素类型不要求统一,mutable的,可以对每个元素进行增删改查。可以按照index删除元素(pop),也可以按照值删除元素(remove),可以插入元素到某个位置(insert),也可以追加元素到列表尾部(append)。
Demo:
testList = [123,"456",[789,"10"]]
print(testList)
print(testList[2])
testList.insert(2,"abc")
print(testList)
testList.remove(2)
print(testList)
Tuple
语法:(123,456,789,100)
特征:小括号包裹,逗号隔开元素,元素类型必须统一,可以嵌套但是满足类型统一,可以用 index 进行读,但不可写,更不可增删。
特点:非mutable 的List,所有操作都类似List,唯一的不同就是只能 查,不能增(没有append和insert)删(没有remove和pop)改(不能对元素赋值)。可以认为 Tuple 是一个 元素类型必须统一且不可修改 的 List,只能读里面的内容。
Demo:
testTuple = (123,456,789,100)
print(testTuple)
print(testTuple[2])
testTuple[3] = 200 #TypeError: 'tuple' object does not support item assignment
Set
语法:{ 1,"23",classObjectA }
特征:大括号包裹,逗号隔开元素,元素类型任意,可以嵌套,可以用index读写。基本和List一致。
特点:可以认为是自动除重的 List ,且不支持排序,其他和 List 没区别。
Demo:
testSet = {123,"456"}
print(testSet)
testSet.add(cv2.VideoCapture(0,cv2.CAP_DSHOW)) #output:{<VideoCapture 000001CA45FCBB90>, '456', 123}
print(testSet)
Dictionary
语法:{
"name" :"zhangsan",
"age":50
}
特征:大括号包裹,逗号隔开元素,元素构成必须统一格式(由分号分隔的两部分,前半部分必须是字符串,后半部分任意),key一定是字符串,如果发现某个元素没包含冒号,则会被当做Set处理,又因为有些元素包含分号,而Set允许元素中出现冒号(字符串中的不算),所以此时会报错。
特点:最灵活的容器,不支持排序,可以嵌套,通过 [ ] 和 get 进行元素访问,不可用 index ,使用 pop 按 key进行元素移除(没有remove)。
Demo:
testDict = {"123":123,
"qwe":"345",
"sub":{
"abc":1,
"q":2
}
}
print(testDict ["sub"]["abc"])
print(testDict .get("sub").get("q"))
使用 in 判断容器中是否包含元素
testList = [123,4,"cc",[123,545]]
print([123,545] in testList) #true
#===================================
testDict = {
"123":123,
"qwe":"345",
"sub":{
"abc":1,
"q":2
}
}
print("sub" in testList) #true
print("345" in testList) #false