首页 > 代码库 > day1:python容器
day1:python容器
python中的容器有:列表、元组、字典和集合
列表
#使用[] 或list() 创建列表 num_list=list([1,2,3,4,5]) name_list=["Jack","Michael","Kangkang"] print(num_list,name_list) #使用list()将其他数据类型转换为列表 #将一个字符串转换成由单个字母组成的列表 li=list("cat dog") print(li) #将一个元组转换成列表 li=list(("first","second","third")) print(li) #使用split()可以依据分隔符将字符串分割成若干个子串组成的列表 birthday="8/5/1976" li=birthday.split("/") print(li) #[‘8‘, ‘5‘, ‘1976‘] #如果待分隔的字符串包含连续的分隔符,那么在返回的列表中会出现空串元素 splitme="a/b//c/d///e" li=splitme.split("/") #[‘a‘, ‘b‘, ‘‘, ‘c‘, ‘d‘, ‘‘, ‘‘, ‘e‘] print(li) li=splitme.split("//") #[‘a/b‘, ‘c/d‘, ‘/e‘] print(li) #使用string.join(str_list)可以把列表转化为字符串 name_list=["Groucho","Chico","Harpo"] result="*".join(name_list) print(result) # Groucho*Chico*Harpo #使用[offset]获取或者修改元素:指定的偏移量对于待访问列表必须有效 #print(marxes[-5],marxes[4]) IndexError: list index out of range marxes=["Groucho","Chico","Harpo"] print(marxes[0],marxes[1],marxes[2]) print(marxes[-1],marxes[-2],marxes[-3]) marxes[2]="Wanda" print(marxes) #指定范围并使用切片获取元素 marxes=["Groucho","Chico","Harpo"] print(marxes[0:2]) #[‘Groucho‘, ‘Chico‘] print(marxes[::2]) #[‘Groucho‘, ‘Harpo‘] print(marxes[::-2]) #[‘Harpo‘, ‘Groucho‘] print(marxes[::-1]) #[‘Harpo‘, ‘Chico‘, ‘Groucho‘] #使用append()添加元素至尾部 marxes.append("Zeppo") print(marxes) #[‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘] #使用insert()在指定位置插入元素,如果偏移量超出了尾部则会插入到列表最后 marxes.insert(0,"Gummo") print(marxes) #[‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘] marxes.insert(10,"Karl") print(marxes) #[‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘] #使用extend或者+=扩展列表 others=["cat","dog"] marxes.extend(others) #[‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘, ‘cat‘, ‘dog‘] print(marxes) marxes+=[11,22,33] #[‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘, ‘cat‘, ‘dog‘, 11, 22, 33] print(marxes) #如果错误的使用了append,这个列表会被当做一个单独的元素添加 marxes=["Groucho","Chico","Harpo"] marxes.append(others) print(marxes) #[‘Groucho‘, ‘Chico‘, ‘Harpo‘, [‘cat‘, ‘dog‘]] #使用del删除指定位置的元素,超出索引报错 num_list=[11,22,33,44,55,66,77,88] del num_list[-1] #[11, 22, 33, 44, 55, 66, 77] print(num_list) del num_list[1] #[11, 33, 44, 55, 66, 77] print(num_list) #使用pop获取并删除指定位置的元素,超出索引报错 num_list=[11,22,33,44,55,66,77,88] result=num_list.pop() #删除最后一个元素,并把这个元素返回给result print(result,num_list) #88 [11, 22, 33, 44, 55, 66, 77] result=num_list.pop(1) #删除第二个元素,并把这个元素返回给result print(result,num_list) #22 [11, 33, 44, 55, 66, 77] #使用remove删除具有指定值的元素 num_list=[11,22,33,44,55,66,77,88,"cat","dog"] num_list.remove(88) num_list.remove("cat") print(num_list) #使用index()查询具有特定值的元素位置 num_list=[11,22,33,44,55,66,77,88,"cat","dog","cat",True] print(num_list.index(11)) # 0 print(num_list.index("cat")) # 8 #使用count()查询特定值出现的次数 print(num_list.count(88)) print(num_list.count("cat")) #删除所有"cat" for i in range(num_list.count("cat")): num_list.remove("cat") print(num_list) #使用len()返回列表长度 print(len([11,22,33,44])) # 4 #使用in 判断是否存在指定的值 print("cat" in num_list) print(True in num_list) #使用sort排序,使用reverse反转 (无返回值,直接更改列表本身) num_list=[5,2,3,1,4] num_list.sort() print(num_list) #[1,2,3,4,5] num_list.reverse() print(num_list) #[5,4,3,2,1] #包含列表的列表 small_birds=["hummingbird","finch"] extinct_birds=["dodo","passenger pigeon","Norwegian Blue"] carol_birds=[3,"French hens",2,"turtledoves"] all_birds=[small_birds,extinct_birds,"macaw",carol_birds] print(all_birds)#[[‘hummingbird‘, ‘finch‘], [‘dodo‘, ‘passenger pigeon‘, ‘Norwegian Blue‘], ‘macaw‘, [3, ‘French hens‘, 2, ‘turtledoves‘]] print(all_birds[0])#[‘hummingbird‘, ‘finch‘] print(all_birds[1])#[‘dodo‘, ‘passenger pigeon‘, ‘Norwegian Blue‘] print(all_birds[1][0])#dodo
[1, 2, 3, 4, 5] [‘Jack‘, ‘Michael‘, ‘Kangkang‘] [‘c‘, ‘a‘, ‘t‘, ‘ ‘, ‘d‘, ‘o‘, ‘g‘] [‘first‘, ‘second‘, ‘third‘] [‘8‘, ‘5‘, ‘1976‘] [‘a‘, ‘b‘, ‘‘, ‘c‘, ‘d‘, ‘‘, ‘‘, ‘e‘] [‘a/b‘, ‘c/d‘, ‘/e‘] Groucho*Chico*Harpo Groucho Chico Harpo Harpo Chico Groucho [‘Groucho‘, ‘Chico‘, ‘Wanda‘] [‘Groucho‘, ‘Chico‘] [‘Groucho‘, ‘Harpo‘] [‘Harpo‘, ‘Groucho‘] [‘Harpo‘, ‘Chico‘, ‘Groucho‘] [‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘] [‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘] [‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘] [‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘, ‘cat‘, ‘dog‘] [‘Gummo‘, ‘Groucho‘, ‘Chico‘, ‘Harpo‘, ‘Zeppo‘, ‘Karl‘, ‘cat‘, ‘dog‘, 11, 22, 33] [‘Groucho‘, ‘Chico‘, ‘Harpo‘, [‘cat‘, ‘dog‘]] [11, 22, 33, 44, 55, 66, 77] [11, 33, 44, 55, 66, 77] 88 [11, 22, 33, 44, 55, 66, 77] 22 [11, 33, 44, 55, 66, 77] [11, 22, 33, 44, 55, 66, 77, ‘dog‘] 0 8 1 2 [11, 22, 33, 44, 55, 66, 77, 88, ‘dog‘, True] 4 False True [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [[‘hummingbird‘, ‘finch‘], [‘dodo‘, ‘passenger pigeon‘, ‘Norwegian Blue‘], ‘macaw‘, [3, ‘French hens‘, 2, ‘turtledoves‘]] [‘hummingbird‘, ‘finch‘] [‘dodo‘, ‘passenger pigeon‘, ‘Norwegian Blue‘] dodo
元组
#元组一旦创建就无法修改,没有append,insert等方法 #使用()或者tuple()创建元组 tu=(11,22,33,44,"cat","Dog",True) print(tu) tu=tuple(range(10)) print(tu) tu=tuple([1,2,3,4,1,2,1]) print(tu) tu=1,2,3 print(tu) print(dir(tu)) #查看所有成员 print(tu.count(1)) #查看指定元素的个数 print(tu.index(1)) #查看指定元素的第一次出现的索引 #元组解包:一口气将元组赋值给多个变量 marx_tuple=("Groucho","Chico","Harpo") a,b,c=marx_tuple print(a,b,c) #可以利用元组在一条语句中对多个变量的值进行交换,而不需要借助临时变量 a="aaa" b="bbb" (a,b)=(b,a) print(a,b)
(11, 22, 33, 44, ‘cat‘, ‘Dog‘, True) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) (1, 2, 3, 4, 1, 2, 1) (1, 2, 3) [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘count‘, ‘index‘] 1 0 Groucho Chico Harpo bbb aaa
元组和列表相比,没有列表灵活,那为什么不在所有地方都使用列表呢?原因如下:
(1)元组占用的空间较小
(2)你不会意外修改元组的值
(3)可以将元组用作字典的键
(4)命名元组可以作为对象的替代
(5)函数的参数是以元组形式传递的
字典
#使用{}创建字典 empty_dict={} print(empty_dict) dic={"k1":"v1","k2":"v2","k3":"v3"} print(dic) #使用dict()转换为字典 dic=dict(k1="v1",k2="v2",k3="v3") print(dic) lol=[["k1","v1"],["k2","v2"],["k3","v3"]] print(dict(lol)) lot=[("k1","v1"),("k2","v2"),("k3","v3")] print(dict(lot)) tol=(["k1","v1"],["k2","v2"],["k3","v3"]) print(dict(tol)) tot=(("k1","v1"),("k2","v2"),("k3","v3")) print(dict(tot)) los=["ab","cd","ef"] #双字符组成的列表 print(dict(los)) tos=("ab","cd","ef") #双字符组成的元组 print(dict(tos)) #通过[key] 或者get(key,default) 获取元素 #通过dict[key]获取元素,key不存在时报错 #通过dict.get(key,default) 获取元素,key不存在时返回设置的默认值,没有设置默认值则返回None print(dic["k1"],dic["k2"],dic["k3"]) print(dic.get("k1"),dic.get("k2","default"),dic.get("k3"),dic.get("k4"),dic.get("k5","default")) #使用keys()获取所有键,values()获取所有值,items()获取所有键值对 for key in dic.keys(): print(key) for value in dic.values(): print(value) for key,value in dic.items(): print(key,value) #del删除具有指定键的元素,pop(key)删除并获取具有指定键的元素 del dic[‘k3‘] print(dic) result=dic.pop(‘k1‘) print(result,dic) #使用clear()删除所有元素 dic1={‘k1‘: ‘v11‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘} dic1.clear() print(dic1) #{} #使用in判断某个键是否存在于一个字典 dic1={‘k1‘: ‘v11‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘} print("k1" in dic1) #True print("k4" in dic1) #False print("v1" in dic1) #False #通过[key]添加或者修改元素 dic["k3"]="v22" #dic中不存在k3键,在dic中添加{"k2":"v22"} dic["k3"]="v3" #dic中已经存在k3键,通过[key]修改 print(dic) # dic={‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} #通过update(add_dict)添加或修改字典 dic.update({"k1":"v11"}) #dic中不存在k1键,在dic中添加{"k1":"v11"} print(dic) dic.update({"k1":"v1"}) #dic中已经存在k3键,通过update修改 print(dic) #{‘k3‘: ‘v3‘, ‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘} #如果添加字典与原字典包含相同的键,添加字典的值将会取代原来的值 dic.update({"k4":"v4","k5":"v5","k1":"v111111111"}) print(dic)#{‘k4‘: ‘v4‘, ‘k1‘: ‘v111111111‘, ‘k2‘: ‘v2‘, ‘k5‘: ‘v5‘, ‘k3‘: ‘v3‘} a={"a":1,"b":2} b={"a":2,"c":3} #达到结果a={"a":1,"b":2,"c":"3"},即原字典有这个key,就不要加进来了 b.update(a) #具有相同key,保留谁的值,作为update的参数,即可完成合并 print(b) #{‘c‘: 3, ‘a‘: 1, ‘b‘: 2} a={"a":1,"b":2} b={"a":2,"c":3} a.update(b) print(a) #{‘c‘: 3, ‘a‘: 2, ‘b‘: 2}
{} {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘} {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘a‘: ‘b‘, ‘e‘: ‘f‘, ‘c‘: ‘d‘} {‘a‘: ‘b‘, ‘e‘: ‘f‘, ‘c‘: ‘d‘} v1 v2 v3 v1 v2 v3 None default k3 k2 k1 v3 v2 v1 k3 v3 k2 v2 k1 v1 {‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘} v1 {‘k2‘: ‘v2‘} {} True False False {‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘} {‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘, ‘k1‘: ‘v11‘} {‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘} {‘k5‘: ‘v5‘, ‘k3‘: ‘v3‘, ‘k4‘: ‘v4‘, ‘k2‘: ‘v2‘, ‘k1‘: ‘v111111111‘} {‘a‘: 1, ‘c‘: 3, ‘b‘: 2} {‘a‘: 2, ‘c‘: 3, ‘b‘: 2}
集合
#通过set()或者{}创建集合,空集合:set(),空字典:{} s1=set() print(type(s1)) print(dir(s1)) s2={1,2,3,3,4,5} print(s2) #使用set()将其他类型(字符串、列表、元组、字典(只有键会被使用))转化为集合 s3=set("letters") print(s3) s4=set([1,2,3,3,4,5]) print(s4) s5=set((1,2,3,3,4,5)) print(s5) s6=set({"k1":"v1","k2":"v2","k3":"v3"}) print(s6) #使用in测试值是否存在 drink={‘martini‘:{‘vodka‘,‘vermouth‘}, ‘black russian‘:{‘vodka‘,‘kahlua‘}, ‘white russian‘:{‘vodka‘,‘cream‘,‘kahlua‘}, ‘manhattan‘:{‘rye‘,‘vermouth‘,‘bitters‘}, ‘screwdriver‘:{‘orange juice‘,‘vodka‘} } print("选择含有伏特加(‘vodka‘)的饮料:") for drink_name,contents in drink.items(): if ‘vodka‘ in contents: print(drink_name) print("选择有伏特加(‘vodka‘),并且没有乳糖(‘cream‘)和苦艾酒(‘vermouth‘)的饮料:") for drink_name,contents in drink.items(): if ‘vodka‘ in contents and ‘cream‘ not in contents and ‘vermouth‘ not in contents: print(drink_name) #上面的判断也可以写成: print("____________") for drink_name,contents in drink.items(): if ‘vodka‘ in contents and not (‘cream‘ in contents or ‘vermouth‘ in contents): print(drink_name) #add(element)添加 #元素不能有重复,如果有1,则True添加不进去,如果有0,则False添加不进去 s1={4,2,3,4,5,} s1.add("element1") s1.add(1) s1.add(False) print(s1) #clear()清空 s1.clear() print(s1) #difference()或- 获得查集(出现在第一个集合而不出现在第二个(和第三个)集合),集合自身不变 #difference_update() 获得查集并返回给集合本身 a={1,2} b={2,3} c={1,4} print(a-b-c) #set() print(a.difference(b,c)) #set() a.difference_update(b,c) print(a) #a=set() #symmetric_difference()或者^获得两个集合的异或集(仅在两个集合中出现一次) #symmetric_difference_update() 获得异或集并返回给集合本身 #这两个函数只能传入一个参数 a={1,2} b={2,3} c={4} print(a.symmetric_difference(b)) #{1,3} print(a^b^c) #{1,3,4} a.symmetric_difference_update(b) #a={1,3} print(a) #intersection() 或者&获得交集 #intersection_update() 获得交集并返回给集合本身 a={1,2} b={2,3} c={2,4} print(a.intersection(b,c)) #{2} print(a&b&c) #{2} a.intersection_update(b,c) #a={2} print(a) #union()或| 获得并集 #update()获得并集并返回给集合本身 a={1,2} b={2,3} c={4,5} print(a.union(b,c)) #{1,2,3,4,5} print(a|b|c) #{1,2,3,4,5} a.update(b,c) #a={1,2,3,4,5} print(a) ‘‘‘ 小结:^(异或) -(差集) &(交集) |(并集) 都可以是多个集合。对应的除了symmetric_difference 和symmetric_difference_update 只能接收一个参数,其他的difference(),difference_update();intersection(),intersection_update();union(),update()都可以接收多个参数 ‘‘‘ #使用issubset()或<=判断是否是子集,使用<判断是否是真子集 #使用issuperset()或>=判断是否是超集,使用>判断是否是真超集 a={1,2,3,4,5} b={1,2,3} print(b.issubset(a),b<=a,b<a) #True True True print(a.issuperset(b),a>=b,a>b) #True True True print(a<=a,a<a) #True False
<class ‘set‘> [‘__and__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__iand__‘, ‘__init__‘, ‘__ior__‘, ‘__isub__‘, ‘__iter__‘, ‘__ixor__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__or__‘, ‘__rand__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__ror__‘, ‘__rsub__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__xor__‘, ‘add‘, ‘clear‘, ‘copy‘, ‘difference‘, ‘difference_update‘, ‘discard‘, ‘intersection‘, ‘intersection_update‘, ‘isdisjoint‘, ‘issubset‘, ‘issuperset‘, ‘pop‘, ‘remove‘, ‘symmetric_difference‘, ‘symmetric_difference_update‘, ‘union‘, ‘update‘] {1, 2, 3, 4, 5} {‘e‘, ‘t‘, ‘r‘, ‘s‘, ‘l‘} {1, 2, 3, 4, 5} {1, 2, 3, 4, 5} {‘k3‘, ‘k2‘, ‘k1‘} 选择含有伏特加(‘vodka‘)的饮料: white russian black russian screwdriver martini 选择有伏特加(‘vodka‘),并且没有乳糖(‘cream‘)和苦艾酒(‘vermouth‘)的饮料: black russian screwdriver ____________ black russian screwdriver {False, 1, 2, 3, 4, 5, ‘element1‘} set() set() set() set() {1, 3} {1, 3, 4} {1, 3} {2} {2} {2} {1, 2, 3, 4, 5} {1, 2, 3, 4, 5} {1, 2, 3, 4, 5} True True True True True True True False
python计数器————未完待续
默认字典
#使用setdefault()和defaultdict()处理缺失的值 #setdefault(key,value) 当键不存在时会在字典中添加一项,如果键存在,则不会改变原来的值 dic={‘first‘:‘1‘,‘second‘:‘2‘,‘third‘:‘3‘} dic.setdefault(‘third‘,‘33‘) dic.setdefault(‘fourth‘,‘4‘) dic.setdefault(‘fifth‘,None) dic.setdefault(‘fifth‘,‘5‘) print(dic) a=int() b=list() c=tuple() print(a,b,c) #a=0 b=[] c=() #defaultdict在创建字典时,对每个新的键都会指定默认值,它的参数是一个函数 #当把函数int作为参数传入时,会按照int()调用,返回整数0 #当把函数list作为参数传入时,会按照list()调用,返回空列表[]; #传入tuple,返回空元组() #传入dict,返回空字典{} from collections import defaultdict num_dict=defaultdict(int) num_dict[‘first‘]=1 num_dict[‘second‘]=2 print(num_dict[‘third‘]) print(num_dict) #函数defaultdict()的参数是一个函数,它的返回值赋给缺失键的值 def f(): return ‘ffff‘ f_dict=defaultdict(f) f_dict[‘first‘]=‘11‘ f_dict[‘second‘]=‘22‘ f_dict[‘third‘]=‘33‘ print(f_dict[‘fourth‘],f_dict[‘fifth‘]) print(f_dict) #list=[11,22,33,44,55,66,77,88,99] #要求返回dic={‘k1‘:[11,22,33,44],‘k2‘:[55,66,77,88,99]} #方法一: num_list=list(range(11,100,11)) dic={} for num in num_list: if num<55: if ‘k1‘ in dic: dic[‘k1‘].append(num) else: dic[‘k1‘]=[num,] else: if ‘k2‘ in dic: dic[‘k2‘].append(num) else: dic[‘k2‘]=[num,] print(dic) #方法二: num_list=list(range(11,100,11)) dic=defaultdict(list) for num in num_list: if num<55: dic[‘k1‘].append(num) else: dic[‘k2‘].append(num) print(dic)
{‘fifth‘: None, ‘second‘: ‘2‘, ‘fourth‘: ‘4‘, ‘first‘: ‘1‘, ‘third‘: ‘3‘} 0 [] () 0 defaultdict(<class ‘int‘>, {‘second‘: 2, ‘first‘: 1, ‘third‘: 0}) ffff ffff defaultdict(<function f at 0x0000000002C9CBF8>, {‘fifth‘: ‘ffff‘, ‘second‘: ‘22‘, ‘fourth‘: ‘ffff‘, ‘first‘: ‘11‘, ‘third‘: ‘33‘}) {‘k2‘: [55, 66, 77, 88, 99], ‘k1‘: [11, 22, 33, 44]} defaultdict(<class ‘list‘>, {‘k2‘: [55, 66, 77, 88, 99], ‘k1‘: [11, 22, 33, 44]})
深浅拷贝原理————未完待续
day1:python容器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。