python的数据结构整理001

列表和元组

1.俩者特点:

1.1都是放置任意数据类型的有序集合。

1.2列表是动态的,可以随意的增删改查。

1.3元组是静态的,无法改变。

针对列表空间的分配,为了减少每次增加/删减操作空间分配的开销,Python每次分配空间时都会额外分配一些。这样的机制(over-allocating)保证了操作的高效性,时间复杂度为O(1)。

In [1]: list001 = []
In [2]: list001.__sizeof__()
Out[2]: 40
In [3]: list001.append(1)
In [4]: list001.__sizeof__()
Out[4]: 72
In [5]: list001.append(2)
In [6]: list001.__sizeof__()
Out[6]: 72
In [7]: list001.append(3)
In [8]: list001.__sizeof__()
Out[8]: 72
In [9]: list001.append(4)
In [10]: list001.__sizeof__()
Out[10]: 72
In [11]: list001.append(5)
In [12]: list001.__sizeof__()
Out[12]: 104
2.一些简单对比

1.对比初始化列表和元组的耗时,明显可以看到元组耗时更少。

kevin@192 ~ % python3 -m timeit 'x=(1,2,3,4,5)'
50000000 loops, best of 5: 6.02 nsec per loop
kevin@192 ~ % python3 -m timeit 'x=[1,2,3,4,5]'
10000000 loops, best of 5: 29.6 nsec per loop

2.对比使用[]和list()创建列表的方法和耗时,明显可以看到[]耗时更少。

kevin@192 ~ % python3 -m timeit 'empty_list = list()'
5000000 loops, best of 5: 40.9 nsec per loop
kevin@192 ~ % python3 -m timeit 'empty_list = []'
20000000 loops, best of 5: 12.8 nsec per loop

3.对比使用reverse函数和[::-1],差距并不大。

python3 -m timeit 'listA = [1,2,3,4,5]' 'ListB = listA[::-1]' 'print(ListB)'
kevin@192 ~ % python3 -m timeit 'listA = [1,2,3,4,5]' 'ListB = listA[::-1]' 'print(ListB)'
100000 loops, best of 5: 3.38 usec per loop
kevin@192 ~ % python3 -m timeit 'listA = [1,2,3,4,5]' 'listA.reverse()' 'print(listA)'
100000 loops, best of 5: 3.28 usec per loop
3.使用场景:

3.1如果存储的数据和数量不变,选用元组更加合适,例如返回经纬度。

3.2如果存储的数据数量是可变的,选用列表是更加合适的。

字典和集合

字典是由一系列由键值配对组成的元素的集合。

字典和集合唯一的区别是 集合是由一系列无序的唯一的元素组成,注意集合本质是一个哈希表。

1.对比初始化字典使用dict()和{},很明显{}耗时更少。

kevin@192 ~ % python3 -m timeit "x={'age':20, 'gender':'male'}"
5000000 loops, best of 5: 43.2 nsec per loop
kevin@192 ~ % python3 -m timeit "x=dict({'age':20, 'gender':'male'})"
2000000 loops, best of 5: 112 nsec per loop
原文地址:https://www.cnblogs.com/jason007/p/15639844.html