PYthon投票程序段以及sorted函数说明
来源:互联网 发布:苏新诗毛糙体简 mac 编辑:程序博客网 时间:2024/06/03 18:59
classCount = {} # 建立一个空字典
for vote in classList: # vote遍历输入的向量
if vote not in classCount.keys(): # 如果classList中的元素没有在classCount字典中
classCount[vote] = 1 # 将此元素写入字典classCount,数量记为1
else:
classCount[vote] += 1 # 如果此元素包含在字典classCount中,将此元素数量加1
sortedClassCount = sorted(classCount.iteritems(), \
key = operator.itemgetter(1), reverse = True)
# sorted 函数排序 classCount.iteritems():输出字典的键值对,“\”在程序命令行中表示此行未结束,可换行继续
# operator.itemgetter(1):用于获取对象的那些维的数据,例中为获取对象的第1位的值,意义为通过第1位的特征进行比较# reverse = :定义升序或者降序,True 为降序,False为升序
return sortedClassCount[0][0] #返回第0位的值,即为classCount中计数最多的特征
operator.itemgetter函数:
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
a = [1,2,3]
>>> b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值
>>> b(a)
2
>>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值
>>> b(a)
(2, 1)
要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值
sorted函数:
Python内置的排序函数sorted可以对list或者iterator进行排序,官网文档见:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,该函数原型为:
sorted(iterable[, cmp[, key[, reverse]]])
参数解释:
(1)iterable指定要排序的list或者iterable,不用多说;
(2)cmp为函数,指定排序时进行比较的函数,可以指定一个函数或者lambda函数,如:
- PYthon投票程序段以及sorted函数说明
- python sorted函数以及operator.itemgetter函数
- python sorted函数以及operator.itemgetter函数
- Python中sort以及sorted函数初探
- Python-sorted与sort,以及模拟内置函数sorted()
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数 【转载】
- Python中的sorted函数以及operator.itemgetter函数 【转载】
- Python中的sorted()函数以及operator.itemgetter()函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Python中的sorted函数以及operator.itemgetter函数
- Eclipse ANT
- 使用LayoutParams设置布局
- Adobe AIR 代码签名证书使用指南
- 【C语言】数组与指针
- 苹果Mac系统开发必备资源
- PYthon投票程序段以及sorted函数说明
- MySQL 索引的创建、删除和查看操作
- java 关于SimpleDateFormat线程安全问题
- GitHub Top 100的Android开源库
- 杭电OJ 2546 01背包问题
- 知道这20个正则表达式,能让你少写1,000行代码
- 射随电路附原理图
- firefox快捷键切换窗口功能
- UAP框架--开发java项目--添加过滤器