Python学习小技巧总结
作者:sinat_34022298 时间:2021-09-21 09:28:49
三元条件判断的3种实现方法
C语言中有三元条件表达式,如 a>b?a:b,Python中没有三目运算符(?:),但Python有它自己的方式来实现类似的功能。这里介绍3种方法:
true_part if condition else false_part
a,b=2,3
c=a if a>b else b
a,b=2,1
c=a if a>b else b
>>> print c
2
利用and-or条件判断的特性来实现三元条件判断
首先介绍一下,and和or的用法:
python 中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值。
无论是列表,元组还是字符串,空表示False,非空表示True
>>> 'python' and [] and (2,3)
[]
>>> 'python' and [2,3] and (3,4)
(3, 4)
or 也是从左到右计算表达式,存在真,则返回第一个为真的值,若均为假,则返回最后一个值。
>>> 'python' or [3,4] or ()
'python'
>>> '' or [] or ()
()
然后,我们利用and-or条件判断的特性来实现三元条件判断:
a,b=2,1
c = (a>b and [a] or [b])[0]
>>> print c
2
使用列表
a,b=2,7
c = [b,a][a>b]
>>> print c
7
分析:若a>b为真,由于真用1表示,因此相当于c=[b,a][1],即c=a
若a>b为假,由于假用0表示,因此相当于c=[b,a][0],即c=b
>>> int(False)
0
>>> int(True)
1
字典(dict)
以下问题都是在用Python写KNN的时候遇到的:
dict_items()
python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行:
1 下面的是按照value的值从大到小的顺序来排序。
dic = {‘a':31, ‘bc':5, ‘c':3, ‘asd':4, ‘aa':74, ‘d':0}
dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)
print(dict)
输出的结果:
[(‘aa', 74), (‘a', 31), (‘bc', 5), (‘asd', 4), (‘c', 3), (‘d', 0)]
下面我们分解下代码:
print dic.items() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是元素d[1]的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
2 对字典按键(key)排序:
dic = {‘a':31, ‘bc':5, ‘c':3, ‘asd':4, ‘aa':74, ‘d':0}
dict= sorted(dic.items(), key=lambda d:d[0])
print(dict)
dict_get()
dic = {‘a':31, ‘bc':5, ‘c':3, ‘asd':4, ‘aa':74, ‘d':0}
dic.get(‘a',1)
31
dic.get(‘d',1)
0
dic.get(‘f',1)
1
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
如果k在字典中,返回D[k],即value值,否则返回d,d默认为None
Image和Ndarray互相转换
import numpy as np
from PIL import Image
img = Image.open(filepath)
img_convert_ndarray = np.array(img)
ndarray_convert_img= Image.fromarray(img_convert_ndarray )
# np.array(object) 这个函数很强大啊,看源码里面给的注释
# object : array_like
# An array, any object exposing the array interface, an object whose
# __array__ method returns an array, or any (nested) sequence.
来源:https://blog.csdn.net/sinat_34022298/article/details/77017013
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
plsql与tsql的语法不同
MYSQL教程:检查数据表和修复数据表
详解利用Pytorch实现ResNet网络之评估训练模型
为FCKeditor2.6添加行距功能(最新修改)
我的javascript小扎
百度百科中的asp词条:什么是asp
Symfony2实现从数据库获取数据的方法小结
Oracle下时间转换在几种语言中的实现
asp使用 sql_dmo 添加新数据库代码
这些有问题的细节设计
![](https://img.aspxhome.com/file/UploadPic/20094/20/wangwang-84s.png)
Oracle 11g安装错误提示未找到wfmlrsvcapp.ear的解决方法
![](https://img.aspxhome.com/file/2023/6/64466_0s.jpg)
设置mysql最大连接数的方法
W3C网页内容无障碍指南2.0(WCAG)
使用tensorflow实现AlexNet
![](https://img.aspxhome.com/file/2023/0/62310_0s.jpg)
增加 javascript 的 trim 函数
uniapp实现支付功能
![](https://img.aspxhome.com/file/2023/4/55964_0s.png)
仿淘宝网站的导航标签效果!
![](https://img.aspxhome.com/file/UploadPic/up/2008110512540282.gif)
一个提高了近10%转化率的改进
![](https://img.aspxhome.com/file/UploadPic/20095/22/sampa-400x582-52s.gif)
使用Filter实现信息的二次检索
![](https://img.aspxhome.com/file/UploadPic/200710/8/2007108192555888s.gif)