您的位置:首页 > 其它

Collcetions系列

2016-02-03 21:16 162 查看
一、count计数器

Count主要是提供统计功能,用于统计字符串里某个字符出现的次数。

使用count前需要导入collcetions模块。

>>>import collections
>>>obj = collections.Counter('adkloalnflasmfa')
>>>print(obj)
Counter({'a': 4, 'l': 3, 'f': 2, 'k': 1, 'd': 1, 'm': 1, 's': 1, 'o': 1, 'n': 1})


遍历counter里面的内容

for item in obj.elements():
print(item)


更新

>>>obj = collections.Counter(['11','22','22','33'])
>>>print(obj)
Counter({'22': 2, '11': 1, '33': 1})
>>>obj.update(['eric','11','11'])
>>>print(obj)
Counter({'11': 3, '22': 2, 'eric': 1, '33': 1})


内置函数

def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D. """
pass

def __copy__(self, *args, **kwargs): # real signature unknown
""" D.copy() -> a shallow copy of D. """
pass

def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass

def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
"""
defaultdict(default_factory[, ...]) --> dict with default factory

The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.

# (copied from class doc)
"""
pass

def __missing__(self, key): # real signature unknown; restored from __doc__
"""
__missing__(key) # Called by __getitem__ for missing key; pseudo-code:
if self.default_factory is None: raise KeyError((key,))
self[key] = value = self.default_factory()
return value
"""
pass

def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass

def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass

default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
"""Factory for default value called by __missing__()."""


方法%内置函数
四、可命名元组

#创建类
MytupleClass = collections.namedtuple('MytupleClass',['x','y','z'])
#创建对象
obj = MytupleClass(11,22,33)
print(obj.x)
print(obj.y)
print(obj.z)
11
22
33
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: