Effective Python 46.使用内置算法与数据结构

1.双向队列

from collections import deque
fifo = deque()
fifo.append(1)
x = fifo.popleft()
print(x)

输出:1

在这里插入图片描述在这里插入图片描述在这里插入图片描述2.有序字典

标准的字典是无序的,在拥有相同键值对的两个dict上迭代,可能出现不同的迭代顺序的情况,是因为快速哈希表的实现方式而导致的.

书中例子实验失败

from random import randint

a = {}
a['foo'] = 1
a['bar'] = 2
while True:
    z = randint(99, 1013)
    b = {}
    for i in range(z):
        b[i] = i
    b['foo'] = 1
    b['bar'] = 2
    for i in range(z):
        del b[i]
    if str(b) != str(a):
        break
print(a)
print(b)
print('Equal?', a == b)

书中期望的输出是(字典值添加顺序的显示会不同)在这里插入图片描述
作者希望使用的orderdict类型

from collections import OrderedDict
第一个字典 = OrderedDict()
第一个字典['foo'] = 1
第一个字典['bar'] = 2
第二个字典 = OrderedDict()
第二个字典['foo'] = 'red'
第二个字典['bar'] = 'blue'

for v1, v2 in zip(第一个字典.values(), 第二个字典.values()):
   print(v1, v2)

输出结果:

1 red
2 blue

在这里插入图片描述在这里插入图片描述
3.带有默认值的字典

在字典中保存计数器时,必须要用稍微麻烦一点的方式,才能实现简答你的功能

stats = {}
key = 'my_counter'
if key not in stats:
    stats[key] = 0
stats[key] += 1

# 下面可以实现上面的内容
from collections import defaultdict
stats = defaultdict(int)
stats['my_counter'] = 1

在这里插入图片描述在这里插入图片描述
4.堆队列(优先级队列)

from _heapq import heappop
from heapq import heappush

a = []
heappush(a, 5)
heappush(a, 3)
heappush(a, 7)
heappush(a, 4)
print(heappop(a), heappop(a), heappop(a), heappop(a))

输出:

3 4 5 7

在这里插入图片描述在这里插入图片描述在这里插入图片描述
5.二分查找

from bisect import bisect_left
x = list(range(10**6))
import time
s = time.time()
i = x.index(991234)
print(time.time() - s)
s = time.time()
i = bisect_left(x, 991234)
print(time.time() - s)

输出:

0.006944179534912109
3.814697265625e-06

在这里插入图片描述在这里插入图片描述
6.与迭代器相关的工具
在这里插入图片描述

static PyTypeObject chain_type = {
      PyVarObject_HEAD_INIT(NULL, 0)
      "itertools.chain",                  /* tp_name */
      sizeof(chainobject),                /* tp_basicsize */
      0,                                  /* tp_itemsize */
      /* methods */
      (destructor)chain_dealloc,          /* tp_dealloc */
      0,                                  /* tp_print */
      0,                                  /* tp_getattr */
      0,                                  /* tp_setattr */
      0,                                  /* tp_reserved */
      0,                                  /* tp_repr */
      0,                                  /* tp_as_number */
      0,                                  /* tp_as_sequence */
      0,                                  /* tp_as_mapping */
      0,                                  /* tp_hash */
      0,                                  /* tp_call */
      0,                                  /* tp_str */
      PyObject_GenericGetAttr,            /* tp_getattro */
      0,                                  /* tp_setattro */
      0,                                  /* tp_as_buffer */
      Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
          Py_TPFLAGS_BASETYPE,            /* tp_flags */
      chain_doc,                          /* tp_doc */
      (traverseproc)chain_traverse,       /* tp_traverse */
      0,                                  /* tp_clear */
      0,                                  /* tp_richcompare */
      0,                                  /* tp_weaklistoffset */
      PyObject_SelfIter,                  /* tp_iter */
      (iternextfunc)chain_next,           /* tp_iternext */
      chain_methods,                      /* tp_methods */
      0,                                  /* tp_members */
      0,                                  /* tp_getset */
      0,                                  /* tp_base */
      0,                                  /* tp_dict */
      0,                                  /* tp_descr_get */
      0,                                  /* tp_descr_set */
      0,                                  /* tp_dictoffset */
      0,                                  /* tp_init */
      0,                                  /* tp_alloc */
      chain_new,                          /* tp_new */
      PyObject_GC_Del,                    /* tp_free */
  };

因为类型定义

#ifdef Py_LIMITED_API
typedef struct _typeobject PyTypeObject; /* opaque */
#else
typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    printfunc tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;

#ifdef COUNT_ALLOCS
    /* these must be last and never explicitly initialized */
    Py_ssize_t tp_allocs;
    Py_ssize_t tp_frees;
    Py_ssize_t tp_maxalloc;
    struct _typeobject *tp_prev;
    struct _typeobject *tp_next;
#endif
} PyTypeObject;
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值