Python编程:掌握常用数据结构和算法
发表时间: 2020-12-09 23:04
序列:可以是字符串、列表、元组、集合、字典、可迭代对象。
word="hello"a,b,c,d,e=wordprint(a,b,c,d,e)out:h e l l o
number=set([1,2,3,4])a,b,c,d=numberprint(a,b,c,d)out:1 2 3 4
n_dict={'a':1,'b':2,'c':3,'d':4}a,b,c,d=n_dictprint(a,b,c,d)e,f,g,h=n_dict.values()print(e,f,g,h)out:a b c d1 2 3 4
m=['mike',178,70]name,height,_=m # 约定俗成使用_接收不需要的元素。print(name,height)out:mike 178
record=['mike',30,178,70,1333331,13333332]name,age,height,weight,*phone=recordprint(name,age,height,weight,phone)out:mike 30 178 70 [1333331, 13333332]
nums=(3,1,5,-1,8,10,11)print(max(nums))print(min(nums))out:11-1
import heapqnums=(3,1,5,-1,8,10,11)print(heapq.nlargest(3,nums))print(heapq.nsmallest(3,nums))out:[11, 10, 8][-1, 1, 3]
table=[{'a':1},{'a':2},{'b':0},{'b':1},{'c':5}]d={}for i in table: for k,v in i.items(): if k not in d: d[k]=[] d[k].append(v)print(d)out:{'a': [1, 2], 'b': [0, 1], 'c': [5]}12345678910
shares={'南钢股份':3.34,'攀钢钒钛':3.36,'马钢股份':3.5,'山东钢铁':3.55,'博汇纸业':3.59,'紫金矿业':3.6}min_shares=min(shares,key=lambda x:shares[x])print(min_shares,shares[min_shares])out:南钢股份 3.34
shares={'南钢股份':3.34,'攀钢钒钛':3.36,'马钢股份':3.5,'山东钢铁':3.55,'博汇纸业':3.59,'紫金矿业':3.6}max_shares=max(shares,key=lambda x:shares[x])print(max_shares,shares[max_shares])out:紫金矿业 3.6
shares={'南钢股份':3.34,'攀钢钒钛':3.36,'马钢股份':3.5,'山东钢铁':3.55,'博汇纸业':3.59,'紫金矿业':3.6}sorted_shares=sorted(shares,key=lambda x:shares[x])print(sorted_shares)print({x:shares[x] for x in sorted_shares})out:['南钢股份', '攀钢钒钛', '马钢股份', '山东钢铁', '博汇纸业', '紫金矿业']{'南钢股份': 3.34, '攀钢钒钛': 3.36, '马钢股份': 3.5, '山东钢铁': 3.55, '博汇纸业': 3.59, '紫金矿业': 3.6}
shares={'南钢股份':3.34,'攀钢钒钛':3.36,'马钢股份':3.5,'山东钢铁':3.55,'博汇纸业':3.59,'紫金矿业':3.6}sorted_shares=sorted(shares,key=lambda x:-shares[x])print(sorted_shares)print({x:shares[x] for x in sorted_shares})out:['紫金矿业', '博汇纸业', '山东钢铁', '马钢股份', '攀钢钒钛', '南钢股份']{'紫金矿业': 3.6, '博汇纸业': 3.59, '山东钢铁': 3.55, '马钢股份': 3.5, '攀钢钒钛': 3.36, '南钢股份': 3.34}
x = {'a':1,'b':2,'c':3}y = {'b':5,'c':6,'d':7}z1 = {key:x[key] for key in x.keys()&y.keys() }z2 = {key:y[key] for key in x.keys()&y.keys() }print(z)print(z1)print(z2)out:{'c', 'b'}{'c': 3, 'b': 2}{'c': 6, 'b': 5}
x = {'a':1,'b':2,'c':3}y = {'b':5,'c':6,'d':7}z1 = {key:x[key] for key in x.keys()-y.keys() }z2 = {key:y[key] for key in y.keys()-x.keys() }print(z1)print(z2)out:{'a': 1}{'d': 7}
说明:字典的键可以做集合的运算(交集、并集、差集、异或集),因为字典的键和集合的元素都是可哈希的(hashable),如果需要对字典的值进行集合运算,那么要将字典的值转成集合或将字典的值与键对换。另外请牢记不可变数据类型才是可哈希的,可变数据类型不可哈希。
x = {'a':1,'b':2,'c':3}y = {x[i]:i for i in x}print(y)out:{1: 'a', 2: 'b', 3: 'c'}
x={'a':1,'b':2,'c':3,'d':4}result = {key:x[key] for key in x if x[key]%2==0}print(result)out:{'b': 2, 'd': 4}
x={'a':1,'b':2,'c':3,'d':4}y={'c':100,'d':200,'e':5,'f':6}z={'g':10,'h':11,'i':12,'j':13}from collections import ChainMapmy_dict= ChainMap(x,y,z)print(my_dict)my_dict['c']=33print(x)print(y)print(my_dict['a'],my_dict['e'],my_dict['i'])out:ChainMap({'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'c': 100, 'd': 200, 'e': 5, 'f': 6}, {'g': 10, 'h': 11, 'i': 12, 'j': 13}){'a': 1, 'b': 2, 'c': 33, 'd': 4}{'c': 100, 'd': 200, 'e': 5, 'f': 6}1 5 12
说明:ChainMap是类,可以将多个字典当作参数创建它的实例,这个实例可以当作字典来使用。它有几个特点:
x=[1,2,3,2,3,5,6,0,-1,3,8]y=list(dict.fromkeys(x))print(y)out:[1, 2, 3, 5, 6, 0, -1, 8]
说明:dict.fromkeys()是建字典的方法,第一个参数是键,第二个参数是值(缺省值是None)。自从python3.6版本以后字典是有序的,顺序即按元素添加的顺序。
letter = 'There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do'.split(' ')from collections import Counterwordcount= Counter(letter) # 创建Counter类的统计实例:wordcountprint(wordcount.most_common(3)) # 打印wordcount中出现次数最多的3个元素及出现次数letter2 = 'May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.'.split(' ')wordcount.update(letter2) # wordcount实例更新letter2文章print(wordcount.most_common(3)) # 打印更新以后出现次数最多的3个元素及出现次数out:[('you', 7), ('to', 6), ('want', 5)][('you', 13), ('to', 10), ('want', 5)]
nums= [1,3,5,-1,-2,0,8]result = [i for i in nums if i>0]print(result)out:[1, 3, 5, 8]
nums= [1,3,5,-1,-2,0,8]result= list(filter(lambda x:x>0,nums))print(result)out:[1, 3, 5, 8]
说明:高阶函数filter有2个参数:第一个参数是用来判断的函数(该函数对第二参数中的每一个元素进行运算,返回True或False),第二参数是可迭代序列;返回值是迭代器,在大量数据需要筛选时优先节省内存时建议用迭代器。
nums = [1,3,5,-1,-2,0,8]big0 = [i>0 for i in nums]print(big0)import itertoolsresult= list(itertools.compress(nums,big0))print(result)out:[True, True, True, False, False, False, True][1, 3, 5, 8]
说明:compress函数有2个参数,第一个参数是数据源可迭代序列,第二个参数是与第一个参数等长的可迭代序列(内部元素是True或False);返回值是可迭代序列,内部元素是第一参数的可迭代序列中对应第二参数可迭代序列值为True的元素。