惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
P
Privacy International News Feed
Hugging Face - Blog
Hugging Face - Blog
U
Unit 42
博客园 - 叶小钗
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
T
Tor Project blog
阮一峰的网络日志
阮一峰的网络日志
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Help Net Security
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
I
Intezer
L
LINUX DO - 最新话题
Blog — PlanetScale
Blog — PlanetScale
T
The Exploit Database - CXSecurity.com
Hacker News - Newest:
Hacker News - Newest: "LLM"
酷 壳 – CoolShell
酷 壳 – CoolShell
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Webroot Blog
Webroot Blog
WordPress大学
WordPress大学
A
About on SuperTechFans
P
Proofpoint News Feed
T
Tailwind CSS Blog
I
InfoQ
The Register - Security
The Register - Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AWS News Blog
AWS News Blog
博客园 - Franky
Simon Willison's Weblog
Simon Willison's Weblog
Last Week in AI
Last Week in AI
博客园 - 聂微东
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Attack and Defense Labs
Attack and Defense Labs
T
Tenable Blog
大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
W
WeLiveSecurity
S
Security @ Cisco Blogs
MongoDB | Blog
MongoDB | Blog

Posts on WKLKEN THINKING

apisix 中的 lrucache apisix 中的服务发现机制 apisix 中的负载均衡 apisix etcd机制 聊聊框架 关于 k8s 的 zero downtime deployment 一些建议 apisix 遇到的一些问题 关于在除夕前一天换了一个洗衣机的故事 Django DRF 性能优化 DRF 的一些实践 Part1: Serializer DRF继承关系图 Better Code: 关于接口的灵活性 新的仓库: wklken/naming 缓存使用的一些经验 Better Code: 抽象: 可扩展性与可维护性的抉择 Better Code: 异常时, 该提示用户哪些信息? Better Code: 更好的异常日志打印 Go: some libs Go: go-redis/cache升级的坑 Go: logrus性能提升 Go: gin validation 远程办公的一点总结 Go: 开发过程中的一些bug 项目管理实践: 风险驱动开发 Go: 一种error wrap调用链处理方式 漫谈技术选型 Go: 基于 apitest 做handler层单元测试 Go: go-sql-driver interpolateparams参数优化 [分享]深度工作 你需要更多的思考时间 Django项目重构小结 工作七年小结: 学习,生活及其他 [分享]bash日常: bash-utils 极客时间推广海报 2017总结: 予时光以意义 k8s APIServer源码: api注册详细细节 k8s APIServer源码: api注册主体流程 k8s APIServer源码: 服务启动 k8s APIServer源码: go-restful框架 重构 - 读书笔记(Python示例) 写给新人的沟通建议 vim 杂谈 - 关于快速编辑 vim 杂谈 - 关于移动 读书笔记-重构: 章11 处理概括关系 读书笔记-重构: 章10 简化函数调用 读书笔记-重构: 章9 简化表达式 读书笔记-重构: 章8 重新组织数据 读书笔记-重构: 章7 在对象之间搬移特性 读书笔记-重构: 章6 重新组织函数 Python 代码规范小结 [分享]关于vim ElasticSearch集群部署文档 Logstash+ElasticSearch处理mysql慢查询日志 [分享]关于代码调试DE那些事 Logstash+ElasticSearch+Kibana- 实现相对通用的数据收集分析 ELK维护的一些点(二) [分享]Python源码剖析-数据结构 一些Centos Python生产环境的部署命令 摘录<<6个月学会任何一种外语>> ELK 维护的一些点 也许是一个新的开始 一些vim的个性化配置 读书笔记-调试九法 这段时间的一些想法 Python 源码阅读 - 垃圾回收机制 我为什么要写博客 APUE笔记-第一章 UNIX基础知识 Python源码阅读-闭包的实现 Python源码阅读-内存管理机制(二) Python源码阅读-内存管理机制(一) '活动'设计的一些trick 一些简单的Python测试题 我的tmux配置及说明【k-tmux】 Review and Restart 工作四周年小结 vim插件: surround & repeat[成对符号编辑] vim插件: gundo[时光机] vim插件: expand-region[区域选中] vim插件: quickrun[快速执行] vim插件: trailing-whitespace[行尾空格处理] vim插件: closetag[成对标签补全] vim插件: ctrlp[文件搜索] vim插件: airline[状态栏增强] vim插件: theme[主题] vim插件: tagbar[大纲式导航] vim插件: nerdcommenter[快速注释] vim插件: rainbow_parentheses[括号高亮] vim插件: syntastic[语法检查] vim插件: delimitmate[符号自动补全] vim插件: matchit[成对标签跳转] vim插件: easy-align[快速对齐] vim插件: multiple-cursors[多光标操作] vim插件: vim-signature[快速标记跳转] vim插件: easymotion[快速跳转] vim插件: vundle[管理插件] Elasticsearch几个问题的解决 分享一份 Vim 简介PPT k-vim 更新9.0版本 关于知识管理工具的思考 Logstash+ElasticSearch+Kibana处理nginx访问日志
Python-基础-数据结构小结
2015-08-28 · via Posts on WKLKEN THINKING

只是一篇笔记, 梳理了下

====================

序列

string

基本数据结构, 不解释

可以看下我之前的笔记

list

基本数据结构, 不解释

可以看下我之前的笔记

tuple

基本数据结构, 不解释

可以看下我之前的笔记

namedtuple

在collections中, 从名字可以看出是命名的tuple

collections.namedtuple(typename, field_names[, verbose=False][, rename=False])

好处, 文档中提到

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

和一般class+自定义__slots__的功能类似, 不会给每个实例定义__dict__, 可以节省内存

所以, 优点

1. 可读性更好, 可以当做轻量的类来使用(only attributes)
2. 节省内存

文档的例子

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Point(x=%r, y=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')


>>> p = Point(x=11, y=22)
>>> p.x, p.y
(11, 22)
>>> p[0], p[1]
(11, 22)
>>> p
Point(x=11, y=22)

array

python 2 library: array

数组, 和列表的区别是, 一个数组只能存储一种类型的数据(即数组中所有元素类型一致), 类型是有限的集合

相对的, 优点是: 节省内存

class array.array(typecode[, initializer])

# 其中, typecode
Type code   C Type                            Python Type Minimum size in bytes
'c'         char                              character   1
'b'         signed char                       int         1
'B'         unsigned char                     int         1
'u'         Py_UNICODE          Unicode character         2(see note)
'h'         signed short                      int         2
'H'         unsigned short                    int         2
'i'         signed int                        int         2
'I'         unsigned int                      long        2
'l'         signed long                       int         4
'L'         unsigned long                     long        4
'f'         float                             float       4
'd'         double                            float       8

使用实例

>>> import array
>>> l = array.array('i', [1,2,3,4,5])
>>> l
array('i', [1, 2, 3, 4, 5])
>>> len(l)
5
>>> l[0]
1
>>> l.index(3)
2
>>> l.insert(0, 0)
>>> l
array('i', [0, 1, 2, 3, 4, 5])

linked list

似乎要在Python中用这个的场景非常之少…..

也似乎有两种选择

  1. 自己写一个
  2. 用其他数据结构替代

具体可以看看这个 Python Linked List

set

base set

基本数据结构, 不解释

可以看下我之前的笔记

frozenset

标准库带, 简而言之: frozenset是set的不可变版本, 类似tuple和list的关系

文档

frozenset可以作为字典键

>>> s = set([1,2,2,3])
>>> s.add(4)
>>> s.add(4)
>>> s
set([1, 2, 3, 4])
>>> hash(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>>
>>> s2 = frozenset([1, 2, 2, 3])
>>> s2
frozenset([1, 2, 3])
>>> s2.add(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>
>>> hash(s2)
-7699079583225461316

dict

base dict

基本数据结构, 不解释

可以看下我之前的笔记

ordered dict

dict的子类, 会记住放入字典键值对的顺序, 文档

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>>
>>> d[3] = 'c'
>>> d[1] = 'b'
>>> d[2] = 'a'
>>> d
OrderedDict([(3, 'c'), (1, 'b'), (2, 'a')])
>>> d.items()
[(3, 'c'), (1, 'b'), (2, 'a')]
>>> d.items()
[(3, 'c'), (1, 'b'), (2, 'a')]
>>>
>>>
>>> d2 = dict()
>>> d2[3] = 'c'
>>> d2[1] = 'b'
>>> d2[2] = 'a'
>>> d2
{1: 'b', 2: 'a', 3: 'c'}
>>> d2.items()
[(1, 'b'), (2, 'a'), (3, 'c')]

default dict

defaultdict, 同样是dict的子类, 会自动设置value的默认值, 文档

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> d['a'].append(1)
>>> d
defaultdict(<type 'list'>, {'a': [1]})
>>> d['a']
[1]
>>> d['a'].append(2)
>>> d['a']
[1, 2]
>>> d['notexists']
[]

others - MultiDict

一键多值的dict

bottle里面的MultiDict

werkzeug里面的版本

>>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True

others - CaseInsensitiveDict

key大小写不明感的dict

CaseInsensitiveDict

cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json'  # True

others - CallbackDict

更新时会调用回调函数

CallbackDict

stack

Python标准库没有stack实现, 如果要处理, 可以自己写一个, 或者使用现有数据结构替代

use list as stack

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return len(self.items) == 0

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)

queue

base queue

use list as queue

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return len(self.items) == 0

    def enqueue(self, item):
        self.items.insert(0, item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

其他, python标准库中的Queue模块, 文档

包含

Queue    FIFO
LifoQueue  LIFO
PriorityQueue  带优先级的

多用于多线程资源共享中(一般情况下很少用), 因为是线程安全的

deque

双端队列, 线程安全, 且左右两端出入队复杂度O(1), 文档

>>> from collections import deque
>>> d = deque([1, 2, 3])
>>> d
deque([1, 2, 3])
>>> d.append(4)
>>> d.appendleft(0)
>>> d
deque([0, 1, 2, 3, 4])
>>>
>>> d.pop()
4
>>> d
deque([0, 1, 2, 3])
>>> d.popleft()
0
>>> d
deque([1, 2, 3])

最小堆实现

文档

>>> import heapq
>>>
>>> h = []
>>> heapq.heappush(h, (5, 'e'))
>>> heapq.heappush(h, (1, 'a'))
>>> heapq.heappush(h, (2, 'b'))
>>> heapq.heappush(h, (4, 'd'))
>>> heapq.heappush(h, (3, 'c'))
>>>
>>> h
[(1, 'a'), (3, 'c'), (2, 'b'), (5, 'e'), (4, 'd')]
>>> heapq.heappop(h)
(1, 'a')
>>> h
[(2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
>>> heapq.heappop(h)
(2, 'b')
>>> h
[(3, 'c'), (5, 'e'), (4, 'd')]

标准库没有tree的实现

可以看看这本书的讲解 Introductory Programming in Python Advanced Data Structures: Trees

base tree

自己写一个>_<

import collections

def Tree():
    return collections.defaultdict(Tree)

binary tree

二叉树, 关注下这个包 bintree

包括二叉树/红黑树/AVL树

这个暂时没有好的推荐, 一般处理成二维数组, 或者使用类机制实现节点/边

其他

计数counter

Counter文档

dict子类, 会记录某个key出现的次数, 在做计数/统计的时候非常有用

>>> from collections import Counter
>>> c = Counter('abracadabra')
>>> c
Counter({'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
>>> c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

bisect

bisect, 维持一个有序列表, 可以用于快速检索

>>> import bisect
>>> bisect.insort_left(l, 1)
>>> bisect.insort_left(l, 5)
>>> bisect.insort_left(l, 2)
>>> bisect.insort_left(l, 7)
>>> l
[1, 2, 5, 7]

>>> bisect.bisect_left(l, 2)  # 返回位置或插入后的位置
1
>>> bisect.bisect_left(l, 20)
4

struct

处理和存储二进制数据的时候用到, 文档

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)