Python标准库之collections

1. collections 之 Counter

案例1:

print(y_pred)  # len(y_pred)=88

输出:

Out[1]: 
array([2, 1, 2, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 3, 5, 3, 3, 3, 3, 5, 4, 3,
       3, 3, 3, 4, 5, 5, 4, 4, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 5, 1, 1,
       1, 1, 1, 1, 1, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 0, 1, 4, 4, 0, 0, 0,
       4, 4, 4, 4, 4, 1, 3, 4, 5, 5, 5, 5, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4])
from collections import Counter

print(Counter(y_pred))

输出:

Counter({2: 5, 1: 13, 4: 26, 0: 19, 3: 13, 5: 12})

按字典中的 key 进行排序

print(sorted(Counter(y_pred).items(), key=lambda x: x[0], reverse=False))
# key=lambada:匿名函数
# x:x【0】取第1列数据

输出:

[(0, 19), (1, 13), (2, 5), (3, 13), (4, 26), (5, 12)]  # list格式

案例2:

from collections import Counter
c = Counter('gallahad')
c
Out[17]: Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd':1})
dict(c)
Out[18]: {'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1}

处理重复列

b = ['age','sex','occupation','age']
c = dict(Counter(b))
c
Out[21]: {'age': 2, 'sex': 1, 'occupation': 1}

h_c = [k for k, value in c.items() if value>1]  # 选出重复列'age'
h_c
Out[24]: ['age']

案例3

from collections import Counter

a = np.where(np_subdf[:,2]==np_subdf_ori[:,2], 'same', 'different')
Counter(a)
Out[19]: Counter({'same': 3600})

2. collections 之 namedtuple

Python中存储系列数据,比较常见的数据类型有list,除此之外,还有tuple数据类型。

相比与list,tuple中的元素不可修改,在映射中可以当键使用。tuple元组的item只能通过index访问,collections模块的namedtuple子类不仅可以使用item的index访问item,还可以通过item的name进行访问。

from collections import namedtuple

coordinate = namedtuple('Coordinate', ['x', 'y'])
co = coordinate(10,20)
print(co.x,co.y)
print(co[0],co[1])
co = coordinate._make([100,200])
print(co.x,co.y)
co = co._replace(x = 30)
print(co.x,co.y)

results:
10 20
10 20
100 200
30 200

from collections import namedtuple
 
websites = [
    ('Sohu', 'http://www.sohu.com/', u'张朝阳'),
    ('Sina', 'http://www.sina.com.cn/', u'王志东'),
    ('163', 'http://www.163.com/', u'丁磊')
]
 
Website = namedtuple('Website', ['name', 'url', 'founder'])
 
for website in websites:
    website = Website._make(website)
    print(website)

results:

Website(name=‘Sohu’, url=‘http://www.google.com/’, founder=u’\u5f20\u671d\u9633’)
Website(name=‘Sina’, url=‘http://www.sina.com.cn/’, founder=u’\u738b\u5fd7\u4e1c’)
Website(name=‘163’, url=‘http://www.163.com/’, founder=u’\u4e01\u78ca’)

3. collections 之 Iterable

'''
使用内置函数isinstance 判断,例如判断列表是否可迭代
'''
from collections import Iterable
isinstance([], Iterable)## Output: True
  • 如何判断对象是否为迭代器
'''
使用内置函数isinstance 判断,例如判断列表是否可迭代
'''
from collections import Iterator
isinstance([], Iterator)## Output: False, 因为list还没有被转为迭代器,仅是可迭代对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值