Python字典排序问题
字典的问题
navagation:
*1.问题来源
*2.dict的学习
*[3.numpy的应用](#3numpy 函数使用)
1.问题来源
在做cs231n,assigment1-kNN实现的时候,需要对一个列表中的元素进行计数,并找出个数最多的元素
问题本身不是很难,但是运用python字典dict发现自己对字典的理解还是有些欠缺
def predict_labels(self, dists, k=1):
"""
Given a matrix of distances between test points and training points,
predict a label for each test point.
Inputs:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
gives the distance betwen the ith test point and the jth training point.
Returns:
- y: A numpy array of shape (num_test,) containing predicted labels for the
test data, where y[i] is the predicted label for the test point X[i].
"""
num_test = dists.shape[0]
y_pred = np.zeros(num_test)
for i in range(num_test):
# A list of length k storing the labels of the k nearest neighbors to
# the ith test point.
closest_y = []
#########################################################################
# TODO: #
# Use the distance matrix to find the k nearest neighbors of the ith #
# testing point, and use self.y_train to find the labels of these #
# neighbors. Store these labels in closest_y. #
# Hint: Look up the function numpy.argsort. #
#########################################################################
order=np.argsort(dists[i,:])
closest_y=self.y_train[order[:k]]
#########################################################################
# TODO: #
# Now that you have found the labels of the k nearest neighbors, you #
# need to find the most common label in the list closest_y of labels. #
# Store this label in y_pred[i]. Break ties by choosing the smaller #
# label. #
#########################################################################
#closest_dict=dict(closest_y)
#dict_key=sorted(closest_dict.keys(),reverse=True)
#y_pred[i]=dict_key[0]
########## 转换成字典这个想法确实不太对 #####################
c=Counter(closest_y)
y_pred[i]=sorted(c.keys(),reverse=True)[0]
########## 利用Counter来生成字典 #####################
#y_pred[i]=np.argmax(np.bincount(closest_y))
return y_pred
2.字典dict
字典的生成
利用dict函数
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
利用Counter可以实现将 array 转换成计数dict
from collections import Counter
a=[4,8,4,7,9,9]
dict_a=Counter(a)
print(dict_a)
#dict{'4':2,'7':1,'8':1,'9':2}
原始的字典中元素是不存在顺序的。
形如 dic = {'a':1 , 'b':2 , 'c': 3},字典中的元素没有顺序,所以dic[0]是有语法错误的
字典排序的实现
根据键进行排序
根据键值进行排序
使用内建的sorted()函数
sorted(iterable ,key=None, reverse=False)
- key 排序的根据,可以是键,可以是键值
- reverse 是升序还是降序,默认False是升序排序
# 常用形式
dic = {'a':3 , 'b':2 , 'c': 1}
sorted(dic.items(),key=lambda d:d[0],reverse=True)
# {'c':1,'b':2,'a':3}
sorted(dic.items(),key=lambda d:d[1],reverse=True)
# 这个是按字典的第二个元素来进行排序
# {'a':3,'b':2,'c':1}
注意
无论怎么进行排序,字典还是原来的字典顺序
python2中的迭代对象是 iteritems()
items() 迭代器返回字典的键值对,
>>> dict.items()
dict_items([('a', 3), ('b', 2), ('c', 1)])
lambda表达式
#创建一个匿名函数对象
>>> func=lambda x:x+2
>>> func(2)
4
在函数sorted(dic.items(), key = lambda asd:asd[1])中,第一个参数传给第二个参数“键-键值”,第二个参数取出其中的键([0])或键值(1])
3.numpy 函数使用
找到数组中出现次数最多的元素,在vote投票函数中很有用
使用bincount函数实现更简单
>>> import numpy as np
>>> y=[3,3,5,6,7,9,9,8,8,8]
>>> np.bincount(y)
array([0, 0, 0, 2, 0, 1, 1, 1, 3, 2])
>>> np.argmax(np.bincount(y)) # 找到元素
8
>>>
Python字典排序问题的更多相关文章
- Python字典和集合
Python字典操作与遍历: 1.http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html 2.http://5iqiong. ...
- python 字典排序 关于sort()、reversed()、sorted()
一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...
- python字典中的元素类型
python字典默认的是string item={"browser " : 'webdriver.irefox()', 'url' : 'http://xxx.com'} 如果这样 ...
- python字典copy()方法
python 字典的copy()方法表面看就是深copy啊,明显独立 d = {'a':1, 'b':2} c = d.copy() print('d=%s c=%s' % (d, c)) Code1 ...
- python 字典实现类似c的switch case
#python 字典实现类似c的switch def print_hi(): print('hi') def print_hello(): print('hello') def print_goodb ...
- python字典的常用操作方法
Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串.数字.元组等其他容器模型.本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建.访问.删除.其它操作等,需 ...
- Python 字典(Dictionary)操作详解
Python 字典(Dictionary)的详细操作方法. Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串.数字.元组等其他容器模型. 一.创建字典 字典由键和对应值成对组成.字 ...
- Python 字典(Dictionary) get()方法
描述 Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值. 语法 get()方法语法: dict.get(key, default=None) 参数 ...
- Python 字典(Dictionary) setdefault()方法
描述 Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值. 语法 setdefault()方法语法: ...
随机推荐
- JNDI总结(一)
一.数据源的由来 在Java开发中,使用JDBC操作数据库的四个步骤如下: ①加载数据库驱动程序(Class.forName("数据库驱动类");) ②连接数据库(Conn ...
- 内容汇总(c语言)
一,内容 常量(整型,浮点型,字符型,字符串型,符号常量) 变量(基本类型:整形,浮点型,字符型,枚举型:构造类型:数组,结构体,共用体:另外还有指针类型和NULL) 顺序结构 分支结构 循环结构 当 ...
- Spring浅入浅出——不吹牛逼不装逼
Spring浅入浅出——不吹牛逼不装逼 前言: 今天决定要开始总结框架了,虽然以前总结过两篇,但是思维是变化的,而且也没有什么规定说总结过的东西就不能再总结了,是吧.这次总结我命名为浅入浅出,主要在于 ...
- DesignPattern系列__06迪米特原则
迪米特原则定义 迪米特原则,也叫最少知道原则,即一个类应该对自己依赖的类知道的越少越好,而你被依赖的类多么复杂,对我都没有关系.也就是说,对于别依赖的类来说,不管业务逻辑多么复杂,都应该尽量封装在类的 ...
- Linux下安装jupyter
又是美好的一天 开开心心写代码 1. 安装ipython, jupyter pip install ipython pip install jupyter 2. 生成配置文件[root@50e ...
- Flink 源码解析 —— 源码编译运行
更新一篇知识星球里面的源码分析文章,去年写的,周末自己录了个视频,大家看下效果好吗?如果好的话,后面补录发在知识星球里面的其他源码解析文章. 前言 之前自己本地 clone 了 Flink 的源码,编 ...
- 转载 | textarea 在浏览器中固定大小和禁止拖动
HTML 标签 textarea 在大部分浏览器中只要指定行(rows)和列(cols)属性,就可以规定 textarea 的尺寸,大小就不会改变,不过更好的办法是使用 CSS 的 height 和 ...
- JavaFx应用 星之小说下载器
星之小说下载器 说明: 需要jdk环境 目前只支持铅笔小说网,后续添加更多书源,还有安卓版,敬请期待. 喜欢的话,不妨打赏一波! 软件交流QQ群:690380139 断点下载暂未实现,小说下载途中,一 ...
- 调用链系列(3):如何从零开始捕获body和header
拓展阅读:调用链系列(1):解读UAVStack中的贪吃蛇 调用链系列(2):轻调用链实现 在Java中,HTTP协议的请求/响应模型是由Servlet规范+Servlet容器(如Tomcat)实现的 ...
- 数据库系统原理之SQL(三)
数据库系统原理之SQL(三) 1. SQL的组成 1. 数据查询 2. 数据定义 3. 数据操作 4. 数据控制 2. 数据定义语言 CREATE创建数据库或数据库对象 创建数据库 ~~~ CREAT ...