列表推导式

>>> chars = [ c for c in 'python' ]
>>> chars
['p', 'y', 't', 'h', 'o', 'n']

字典推导式

>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> double_dict1 = {k:v*2 for (k,v) in dict1.items()}
>>> double_dict1
{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}

集合推导式

>>> set1 = {1,2,3,4}
>>> double_set = {i*2 for i in set1}
>>> double_set
{8, 2, 4, 6}

合并字典

>>> x = {'a':1,'b':2}
>>> y = {'c':3, 'd':4}
>>> z = {**x, **y}
>>> z
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

复制列表

>>> nums = [1,2,3]
>>> nums[::]
[1, 2, 3]
>>> copy_nums = nums[::]
>>> copy_nums
[1, 2, 3]

反转列表

>>> reverse_nums = nums[::-1]
>>> reverse_nums
[3, 2, 1]

变量交换

>>> a,b = 1, 2
>>> a ,b = b,a
>>> a
2
>>> b
1

高级拆包

>>> a, *b = 1,2,3
>>> a
1
>>> b
[2, 3]
或者

>>> a, *b, c = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

函数返回多个值(其实是自动packing成元组)然后unpacking赋值给4个变量

>>> def f():
... return 1, 2, 3, 4
...
>>> a, b, c, d = f()
>>> a
1
>>> d
4

列表合并成字符串

>>> " ".join(["I", "Love", "Python"])
'I Love Python'

链式比较

>>> if a > 2 and a < 5:
... pass
...
>>> if 2<a<5:
... pass

yield from

# 没有使用 field from
def dup(n):
for i in range(n):
yield i
yield i # 使用yield from
def dup(n):
for i in range(n):
yield from [i, i] for i in dup(3):
print(i) >>>
0
0
1
1
2
2

in 代替 or

>>> if x == 1 or x == 2 or x == 3:
... pass
...
>>> if x in (1,2,3):
... pass

字典代替多个if else

def fun(x):
if x == 'a':
return 1
elif x == 'b':
return 2
else:
return None def fun(x):
return {"a": 1, "b": 2}.get(x)

有下标索引的枚举

>>> for i, e in enumerate(["a","b","c"]):
... print(i, e)
...
0 a
1 b
2 c

生成器

注意区分列表推导式,生成器效率更高

>>> g = (i**2 for i in range(5))
>>> g
<generator object <genexpr> at 0x10881e518>
>>> for i in g:
... print(i)
...
0
1
4
9
16

默认字典 defaultdict

>>> d = dict()
>>> d['nums']
KeyError: 'nums'
>>> >>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["nums"]
[]

字符串格式化

>>> lang = 'python'
>>> f'{lang} is most popular language in the world'
'python is most popular language in the world'

列表中出现次数最多的元素

>>> nums = [1,2,3,3]
>>> max(set(nums), key=nums.count)
3 或者
from collections import Counter
>>> Counter(nums).most_common()[0][0]
3

读写文件

>>> with open("test.txt", "w") as f:
... f.writelines("hello")

判断对象类型,可指定多个类型

>>> isinstance(a, (int, str))
True
类似的还有字符串的 startswith,endswith >>> "http://foofish.net".startswith(('http','https'))
True
>>> "https://foofish.net".startswith(('http','https'))
True

__str__ 与 __repr__ 区别

>>> str(datetime.now())
'2018-11-20 00:31:54.839605'
>>> repr(datetime.now())
'datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)'

前者对人友好,可读性更强,后者对计算机友好,支持 obj == eval(repr(obj))

使用装饰器

def makebold(f):
return lambda: "<b>" + f() + "</b>" def makeitalic(f):
return lambda: "<i>" + f() + "</i>" @makebold
@makeitalic
def say():
return "Hello" >>> say()
<b><i>Hello</i></b>
不使用装饰器,可读性非常差 def say():
return "Hello" >>> makebold(makeitalic(say))()
<b><i>Hello</i></b>

Python 开发中高级技巧的更多相关文章

  1. python 开发技巧(1)-- 用PyCharm安装第三方库

    在python开发中,我们经常需要安装一些python的第三方类库,包等等,用PyCharm就会安装就会超级方便 1.打开上面的小扳手 2.点击页面左边的Project Interpreter 3.点 ...

  2. Python开发最常犯错误总结10种

    不管是在学习还是工作过程中,人都会犯错.虽然Python的语法简单.灵活,但也一样存在一些不小的坑,一不小心,初学者和资深Python程序员都有可能会栽跟头.本文是Toptal网站的程序员梳理的10大 ...

  3. iOS开发实用技巧—在手机浏览器头部弹出app应用下载提示

    iOS开发实用技巧—在手机浏览器头部弹出app应用下载提示 本文介绍其简单使用: 第一步:在本地建立一个访问的服务端.  打开本地终端,在本地新建一个文件夹,在该文件夹中存放测试的html页面.   ...

  4. Python 开发与接口测试学习笔记

    这是我跟着虫师学习中积累下来的学习笔记,写得比较简单,适合想学习Python开发与接口测试的初学者学习. 一.开发投票系统 1.参考官网文档,创建投票系统. https://docs.djangopr ...

  5. Python开发技术详解PDF

    Python开发技术详解(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1F5J9mFfHKgwhkC5KuPd0Pw 提取码:xxy3 复制这段内容后打开百度网盘手 ...

  6. 【python安装】Windows上安装和创建python开发环境

    1. 在 windows10 上安装python开发环境 Linux和Mac OS都自带python环境,但是Windows没有,所以需要自行安装. 第1步:访问 python官网,下载Windows ...

  7. 30个有关Python的小技巧,给程序员的 30 个基本 Python 贴士与技巧

    30个有关Python的小技巧 2013/07/04 · Python, 开发 · 4 评论 · Python 分享到: 66 本文由 伯乐在线 - Kevin Sun 翻译.未经许可,禁止转载!英文 ...

  8. 《python开发技术详解》|百度网盘免费下载|Python开发入门篇

    <python开发技术详解>|百度网盘免费下载|Python开发入门篇 提取码:2sby  内容简介 Python是目前最流行的动态脚本语言之一.本书共27章,由浅入深.全面系统地介绍了利 ...

  9. 学会这些Python美图技巧,就等着女朋友夸你吧

    一.前言 Python中有许多用于图像处理的库,像是Pillow,或者是OpenCV.而很多时候感觉学完了这些图像处理模块没有什么用,其实只是你不知道怎么用罢了.今天就给大家带了一些美图技巧,让你的图 ...

随机推荐

  1. [driver]linux内核动态加载模块

    问题: 1. 把编译好的模块放到板子/lib/modules对应文件夹下,并且执行了depmod -a, 比如pl2303.ko, 那么下一次插入pl2303的串口线,是否可以识别,也就是自动加载pl ...

  2. linux - camera capture

    //cut a picture#include <stdio.h>#include <stdlib.h>#include <string.h>#include &l ...

  3. IE9 BUG overflow :auto 底部空白解决方案

    今天去升级了到IE9,运行项目的时候发现,我的div显示滚动条时候,用js动态加载进去的内容在光标移动的时候,底部自动被撑大留着空白, IE8 Chrome这些以前都试过 没发现这个问题 研究了好久 ...

  4. Spring MVC学习之三:处理方法返回值的可选类型

    http://flyer2010.iteye.com/blog/1294400 ———————————————————————————————————————————————————————————— ...

  5. 004杰信-关于formSubmit('factorycreate.action','_self')路径的疑惑

    本文材料来源于传智播客,在此说明. 整个项目结构:

  6. 第二百八十节,MySQL数据库-外键链表之一对多,多对多

    MySQL数据库-外键链表之一对多,多对多 外键链表之一对多 外键链表:就是a表通过外键连接b表的主键,建立链表关系,需要注意的是a表外键字段类型,必须与要关联的b表的主键字段类型一致,否则无法创建索 ...

  7. 【BZOJ】1079: [SCOI2008]着色方案(dp+特殊的技巧)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1079 只能想到5^15的做法...........................果然我太弱. 其实 ...

  8. 【BZOJ】1676: [Usaco2005 Feb]Feed Accounting 饲料计算(差分)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1676 太水的一题了.. 差分直接搞. #include <cstdio> #includ ...

  9. 【BZOJ】1639: [Usaco2007 Mar]Monthly Expense 月度开支(二分)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1639 同tyvj1359,http://www.cnblogs.com/iwtwiioi/p/394 ...

  10. XML Publiser For Excel Template

    1.XML Publisher定义数据 2.XML Publisher定义模板 模板类型选择Microsoft Excel,默认输出类型选择Excel,上传.xls模板 3.定义并发程序 4.定义请求 ...