python函数enumerate,operator和Counter使用技巧实例小结
本文实例讲述了python函数enumerate,operator和Counter使用技巧。分享给大家供大家参考,具体如下:
最近看人家的代码,发现了很多python内置的函数和数据结构,可以大大减少我们的代码量(而且人家是优化过的)。python以简洁和强大的库著称,要是什么都自己写的话,太不python了。这里介绍常用的能大大提高我们生活幸福度的小技巧:
enumerate()
这个函数主要用于既要遍历元素又要记下索引。通常我们都会这样写(不能再笨拙了):
for i in range(0,len(list)): print i,list[i]
使用enumerate:
for index,text in enumerate(list): print index,text
itemgetter()
这个和下面的函数在operator库中,通常用在排序中。例如要对一个tuple的列表进行排序,找到第二个值最小的那个tuple。我一开始这样做:
list_of_tuples = [(1,2), (3,4), (5,0)] min_tuple = None minimum = sys.maxint for pair in list_of_tuples: x,y = pair if y < minimum: min_tuple = pair print min_tuple
后来,进化了,这样做:
def snd(pair): x,y = pair return y list_of_tuples = [(1,2), (3,4), (5,0)] min(list_of_tuples, key=snd)
这样看起来好多了,可是我发现人家的代码里是这样做的:
import operator list_of_tuples = [(1,2), (3,4), (5,0)] min(list_of_tuples, key=operator.itemgetter(1)) #use 2nd value
attgetter()
这个函数和上面的函数很像,不同的是,上面是用索引获取对应值,而这里使用属性来获取对应值,就像dict一样。
假如我们有个类Student:
class Student(object): def __init__(self, id, name, marks): self.id = id self.name = name self.marks = marks def __str__(self): return '%s has marks %s' %(self.name, self.marks)
我们有一个学生的实例的列表students,需要从里面找到分最高的。最简介的做法是:
students = [ Student(0, 'Foo', 30), Student(1, 'Bar', 95), Student(2, 'Baz', 80)] best_student = max(students, key=operator.attrgetter('marks')) # don't forget the quotes
collections.Counter()
一看这个函数名,就知道是用来统计个数的~返回的是一个dict,key是各个元素,value是对应的个数。一开始,我并不知道这个函数,都是这样统计的:
d={} for text in list: if not text in d.keys(): d[text]=1 else: d[text]+=1 print d
现在,直接一句话:
counter=collections.Counter(list) print counter
之后获取各元素的个数,使用方法同一般的dict。如果增加元素e1,e2和对应个数,直接counter.update({e1=4,e2=3})就可以。
此外,这个Counter不仅用来数数,还有好多函数方便各种操作,例如:
- counter.most_common(n) 返回数目最多的前n个元素和对应个数
- a.substract(b) 返回一个Counter,Counter a减去Counter b,多的元素个数为正值,少的元素个数为负值
- counter.elements() 返回一个element列表,其中每个元素有多少个就重复多少次
- counter.values() 返回个数列表,通常配合sum(counter.values())
- counter.clear() 重置counter
- del counter[e]删除元素e和它的纪录
- 算数操作:+和- ,对应元素个数加减;|和&,两个counter的并集和交集
关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
您可能感兴趣的文章:
- python中enumerate的用法实例解析
- python中使用enumerate函数遍历元素实例
- python进阶教程之循环相关函数range、enumerate、zip
- Python enumerate索引迭代代码解析
- Python利用operator模块实现对象的多级排序详解
- Python中operator模块的操作符使用示例总结
- Python中Collections模块的Counter容器类使用教程
- 简单掌握Python的Collections模块中counter结构的用法
- Python中使用Counter进行字典创建以及key数量统计的方法
- python3+PyQt5实现自定义窗口部件Counters
- 浅谈python中统计计数的几种方法和Counter详解
- python中enumerate() 与zip()函数的使用比较实例分析
- Python中用于去除空格的三个函数的使用小结
- 实例讲解Python的函数闭包使用中应注意的问题
- 使用Python对IP进行转换的一些操作技巧小结
- python 函数enumerate、id、namedtuple、deque、OrderedDict、Counter
- python常用函数使用方法实例
- 【python】如何批量读取文件夹的所有文件数据,os模块与open函数结合使用实例
- Python input函数使用实例解析
- Python enumerate 使用技巧
- python字符串内建函数操作实例(cmp、str、enumerate、zip等)
- Python基础——一些关于迭代、简单推导及工具函数(zip, enumerate)的技巧
- Python过滤函数filter()使用自定义函数过滤序列实例
- 一波神奇的Python语句、函数与方法的使用技巧总结
- 一波神奇的Python语句、函数与方法的使用技巧总结
- Python列表类型的内建函数使用实例(insert、remove、index、pop等)
- python函数使用参数技巧笔记
- python小技巧——enumerate,operator和Counter
- PHP中功能强大却很少使用的函数实例小结
- python字典(dictionary)使用:基本函数code实例,字典的合并、排序、copy,函数中*args 和**kwargs做形参和实参
- Python中函数的多种格式和使用实例及小技巧