美文网首页
collections 模块的使用

collections 模块的使用

作者: Manchangdx | 来源:发表于2018-03-21 13:47 被阅读0次

判断数据类型

1、Hashable 判断是否可哈希,即是否有哈希值,即是否为可变对象
可变对象没有哈希值,不可变对象有:

In [28]: from collections import Hashable

In [29]: isinstance(9, Hashable)          # 可哈希
Out[29]: True

In [30]: isinstance([1,1,1], Hashable)    # 不可哈希
Out[30]: False

In [31]: hash(9)
Out[31]: 9

In [32]: hash('9')
Out[32]: -2994202699711360999

In [33]: hash([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-35e31e935e9e> in <module>()
----> 1 hash([1,2,3])

TypeError: unhashable type: 'list'

In [34]: hash('Kobe')
Out[34]: 3431019011819211506

In [35]: hash((1,))
Out[35]: 3430019387558

2、Iterable 判断可迭代对象,Iterator 判断迭代器,Generator 判断生成器:

In [38]: from collections import Iterable

In [39]: isinstance('hello', Iterable)         # 可迭代
Out[39]: True

In [40]: isinstance(None, Iterable)            # 不可迭代
Out[40]: False

In [41]: from collections import Iterator

In [42]: isinstance('hello', Iterator)         # 不是迭代器
Out[42]: False

In [43]: isinstance(iter('hello'), Iterator)   # 是迭代器
Out[43]: True

In [221]: from collections import Generator

In [222]: isinstance(iter(range(9)), Generator)         # 不是生成器
Out[222]: False

In [223]: isinstance(iter(range(9)), Iterator)          # 是迭代器
Out[223]: True

In [224]: isinstance((i for i in range(9)), Generator)  # 是生成器
Out[224]: True

In [225]: isinstance((i for i in range(9)), Iterator)   # 自然也是迭代器
Out[225]: True

namedtuple 模块的使用

它是个函数,函数的返回值是一个用来创建类元组的元组子类
此函数的使用格式:namedtuple('名称', [属性list])

In [1]: from collections import namedtuple

# 这个 Point 就是元组类的子类,asdf 是类名,通常它俩写成一样的
In [2]: Point = namedtuple('asdf', ['x', 'y'])  

In [3]: p = Point(1, 2)  # p 就是实例,一个类元组对象

In [4]: p.x
Out[4]: 1

In [5]: p.y
Out[5]: 2

# 这个 asdf 的作用暂时不知,它是类名,通常与 namedtuple 返回值的变量名一致,这里就是随便写的
In [6]: p
Out[6]: asdf(x=1, y=2)  

In [9]: p[0]  # 下标也能用,毕竟是类元组
Out[9]: 1

In [10]: p[1]
Out[10]: 2

相关文章

网友评论

      本文标题:collections 模块的使用

      本文链接:https://www.haomeiwen.com/subject/tocgqftx.html