博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python识别数据结构
阅读量:3922 次
发布时间:2019-05-23

本文共 2830 字,大约阅读时间需要 9 分钟。

thinkpython上的一个识别数据结构,返回描述他们形状的字符串

"""This module contains a code example related toThink Python, 2nd Editionby Allen Downeyhttp://thinkpython2.comCopyright 2015 Allen DowneyLicense: http://creativecommons.org/licenses/by/4.0/"""from __future__ import print_function, division"""This module provides one function, structshape(), which takesan object of any type and returns a string that summarizes the"shape" of the data structure; that is, the type, size andcomposition."""def structshape(ds):    """Returns a string that describes the shape of a data structure.    ds: any Python object    Returns: string    """    typename = type(ds).__name__#这句为了得到名字的方法    # handle sequences    sequence = (list, tuple, set, type(iter('')))    if isinstance(ds, sequence):        t = []        for i, x in enumerate(ds):            t.append(structshape(x))        rep = '%s of %s' % (typename, listrep(t))        return rep    # handle dictionaries    elif isinstance(ds, dict):        keys = set()        vals = set()        for k, v in ds.items():            keys.add(structshape(k))            vals.add(structshape(v))        rep = '%s of %d %s->%s' % (typename, len(ds),                                    setrep(keys), setrep(vals))        return rep    # handle other types    else:        if hasattr(ds, '__class__'):            return ds.__class__.__name__        else:            return typenamedef listrep(t):    """Returns a string representation of a list of type strings.    t: list of strings    Returns: string    """    current = t[0]    count = 0    res = []    for x in t:        if x == current:            count += 1        else:            append(res, current, count)            current = x            count = 1    append(res, current, count)    return setrep(res)def setrep(s):    """Returns a string representation of a set of type strings.    s: set of strings    Returns: string    """    rep = ', '.join(s)    if len(s) == 1:        return rep    else:        return '(' + rep + ')'    return def append(res, typestr, count):    """Adds a new element to a list of type strings.    Modifies res.    res: list of type strings    typestr: the new type string    count: how many of the new type there are    Returns: None    """    if count == 1:        rep = typestr    else:        rep = '%d %s' % (count, typestr)    res.append(rep)if __name__ == '__main__':    t = [1, 2, 3]    print(structshape(t))    t2 = [[1, 2], [3, 4], [5, 6]]    print(structshape(t2))    t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9]    print(structshape(t3))    class Point:        """trivial object type"""    t4 = [Point(), Point()]    print(structshape(t4))    s = set('abc')    print(structshape(s))    lt = zip(t, s)    print(structshape(lt))    d = dict(lt)            print(structshape(d))    it = iter('abc')    print(structshape(it))

转载地址:http://mlhrn.baihongyu.com/

你可能感兴趣的文章
一个大厂面试常问的分布式知识点3pc协议详解
查看>>
阿里的OceanBase数据库世界第一,底层原来使用了Paxos协议
查看>>
Springboot整合redis(一般人都能看懂的Lettuce版本)
查看>>
Springboot整合Websocket案例(后端向前端主动推送消息)
查看>>
SpringBoot整合Netty搭建高性能Websocket服务器(实现聊天功能)
查看>>
一个基础又很重要的知识点:JDBC原理(基本案例和面试知识点)
查看>>
Springboot2.x实现文件上传下载的功能(非常实用的小例子)
查看>>
拿下BAT的offer,这篇汇总的Servlet常见面试题正适合你
查看>>
你知道java反射机制中class.forName和classloader的区别吗?
查看>>
一个简单的案例帮你理解什么是SpringIOC(适合新手理解其思想)
查看>>
Springboot2.x整合mybatis多数据源(注解完整版,亲测成功)
查看>>
java中为什么不推荐使用finalize,知道原因后相信你也不会用了
查看>>
帮你解读什么是Redis缓存穿透和缓存雪崩(包括解决方案)
查看>>
Mysql各种存储引擎对比总结(常用几种)
查看>>
java为我们已经提供了各种锁,为什么还需要分布式锁?
查看>>
一文带你理解mysql中的分区表和合并表(一个常见知识点)
查看>>
Redis5.0数据淘汰策略详解(最新版本,面试常问)
查看>>
为什么 MongoDB 索引选择B-树,而 Mysql 选择B+树(精干总结)
查看>>
面试官:说说 Springboot 中的 javaConfig(基于Spring5.2)
查看>>
你的钱为什么被转走,这篇文章告诉你答案(CSRF详解)
查看>>