python重要的几个内置函数用法

        python内置了很多可以供我们直接调用的函数,这些函数的效率往往都非常高,我们在自己造轮子的同时,也非常有必要了解并且正确使用python给我们提供的大量的内置函数,在前面的博客里面我已经介绍了几个比较常用的函数,这里再介绍几个,它们分别是collections模块下的 Counter函数,deque函数以及defaultdict函数。

      1)Counter函数。Counter函数主要可以用来确定某个可迭代对象里面所有元素出现的次数,常用的可迭代对象一般是list。所以如果传给Counter函数的参数不是可迭代对象的时候,会报错。当然我们也可以使用count函数求出list中某个元素出现的次数。代码如下:

    

from random import sample
from collections import Counter, deque, defaultdict

data = sample(range(0, 10, 1), 6) + sample(range(0, 10, 1), 6)  # list的拼接
item_counts = Counter(data)  # Counter的参数应该是一个可以迭代的对象.可迭代的对象:dict,tuple, dict
print(item_counts)
结果:Counter({3: 2, 4: 2, 7: 2, 8: 2, 2: 1, 5: 1, 6: 1, 9: 1})

大家可以发现Counter函数产生的结果是个字典,字典,字典!是传入的列表中的各个元素,是该元素出现的次数,次数,次数!我们可以很容易的获取里面的元素。

for key, value in item_counts.items():
    print(key, value)
key = item_counts.keys()
value = item_counts.values()
print(key, value)
[9, 1, 0, 4, 7, 5, 3, 5, 6, 2, 0, 1]
Counter({0: 2, 1: 2, 5: 2, 2: 1, 3: 1, 4: 1, 6: 1, 7: 1, 9: 1})
0 2
1 2
2 1
3 1
4 1
5 2
6 1
7 1
9 1
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 9]) dict_values([2, 2, 1, 1, 1, 2, 1, 1, 1])

        使用count函数同样可以实现以上的效果,代码如下:

data = sample(range(0, 10, 1), 6) + sample(range(0, 10, 1), 6)  # list的拼接
item_counts = list(map(lambda x: {x: data.count(x)}, set(data)))
print(data)
print(item_counts)
结果:[0, 4, 7, 8, 9, 3, 3, 4, 7, 1, 0, 6]
      [{0: 2}, {1: 1}, {3: 2}, {4: 2}, {6: 1}, {7: 2}, {8: 1}, {9: 1}]
        2)deque函数。deque函数是一个双端队列,实质上可以理解成是一个list。只不过可以很方便的进行头尾删除、插入等操作。但是删除,插入,遍历deque的时候,如果完全使用list相同的方式.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值