python中bisect和数组array,以及高性能的set和dict

Python 2019-01-30 1226

import bisect

# 用来处理已排序的序列,用来维持已排序的序列,升序  
# 底层二分查找  
insert_list = []  
bisect.insort(insert_list, 3)  
bisect.insort(insert_list, 2)  
bisect.insort(insert_list, 5)  
bisect.insort(insert_list, 6)  

# bisect = bisect_right ,得到元素的位置  
print(bisect.bisect(insert_list, 3))  

print(insert_list)  
# result ---->[2, 3, 5, 6]  

import array  

# array与list的重要区别是array只可以放一种数据类型,list可以放如何类型  
# array效率更高  
my_array = array.array("i") # 指定数据类型  
# Type code   C Type             Minimum size in bytes  
#         'b'         signed integer     1  
#         'B'         unsigned integer   1  
#         'u'         Unicode character  2 (see note)  
#         'h'         signed integer     2  
#         'H'         unsigned integer   2  
#         'i'         signed integer     2  
#         'I'         unsigned integer   2  
#         'l'         signed integer     4  
#         'L'         unsigned integer   4  
#         'q'         signed integer     8 (see note)  
#         'Q'         unsigned integer   8 (see note)  
#         'f'         floating point     4  
#         'd'         floating point     8  
my_array.append(1)  



#dict查找的性能远远大于list  
#在list中随着list数据的增大 查找时间会增大  
#在dict中查找元素不会随着dict的增大而增大  

#1.  dict的key或者set的值 都必须是可以hash的  
#不可变对象 都是可hash的, str, fronzenset, tuple,自己实现的类 __hash__  
#2. dict的内存花销大,但是查询速度快, 自定义的对象 或者python内部的对象都是用dict包装的  
# 3. dict的存储顺序和元素添加顺序有关  
# 4. 添加数据有可能改变已有数据的顺序  

 

标签:Python

文章评论

评论列表

已有0条评论