python的30个编程技巧
1、原地交换两个数字
x, y =10, 20 print(x, y) y, x = x, y print(x, y)
10 20
20 10
2、链状比较操作符
n = 10 print(1 < n < 20) print(1 > n <= 9)
True
False
3、使用三元操作符来实现条件赋值
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
y = 20 x = 9 if (y == 10) else 8 print(x)
8
# 找abc中最小的数
def small(a, b, c):
return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))
0
1
3
3
# 列表推导 x = [m**2 if m>10 else m**4 for m in range(50)] print(x)
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
4、多行字符串
multistr = "select * from multi_row \ where row_id < 5" print(multistr)
select * from multi_row where row_id < 5
multistr = """select * from multi_row where row_id < 5""" print(multistr)
select * from multi_row
where row_id < 5
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
select * from multi_rowwhere row_id < 5order by age
5、存储列表元素到新的变量
testList = [1, 2, 3] x, y, z = testList # 变量个数应该和列表长度严格一致 print(x, y, z)
1 2 3
6、打印引入模块的绝对路径
import threading import socket print(threading) print(socket)
<module 'threading' from 'd:\\python351\\lib\\threading.py'>
<module 'socket' from 'd:\\python351\\lib\\socket.py'>
7、交互环境下的“_”操作符
在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
8、字典/集合推导
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
9、调试脚本
用pdb模块设置断点
import pdb
pdb.ste_trace()
10、开启文件分享
python允许开启一个HTTP服务器从根目录共享文件
python -m http.server
11、检查python中的对象
test = [1, 3, 5, 7] print(dir(test))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
test = range(10) print(dir(test))
['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
12、简化if语句
# use following way to verify multi values if m in [1, 2, 3, 4]: # do not use following way if m==1 or m==2 or m==3 or m==4:
13、运行时检测python版本
import sys
if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
print("sorry, you are not running on python 2.7")
print("current python version:", sys.version)
sorry, you are not running on python 2.7
current python version: 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
14、组合多个字符串
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
['I', 'Like', 'Python']
ILikePython
15、四种翻转字符串、列表的方式
5
3
1
16、用枚举在循环中找到索引
test = [10, 20, 30]
for i, value in enumerate(test):
print(i, ':', value)
0 : 10
1 : 20
2 : 30
17、定义枚举量
class shapes:
circle, square, triangle, quadrangle = range(4) print(shapes.circle) print(shapes.square) print(shapes.triangle) print(shapes.quadrangle)
0
1
2
3
18、从方法中返回多个值
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
1 2 3 4
19、使用*运算符unpack函数参数
def test(x, y, z):
print(x, y, z)
testDic = {'x':1, 'y':2, 'z':3}
testList = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)
z x y
1 2 3
10 20 30
20、用字典来存储表达式
stdcalc = {
"sum": lambda x, y: x + y,
"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
12
6
21、计算任何数的阶乘
import functools result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3) print(result)
6
22、找到列表中出现次数最多的数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4] print(max(set(test), key=test.count))
4
23、重置递归限制
python限制递归次数到1000,可以用下面方法重置
import sys x = 1200 print(sys.getrecursionlimit()) sys.setrecursionlimit(x) print(sys.getrecursionlimit())
1000
1200
24、检查一个对象的内存使用
import sys x = 1 print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节
28
25、使用slots减少内存开支
import sys
# 原始类
class FileSystem(object):
def __init__(self, files, folders, devices):
self.files = files
self.folder = folders
self.devices = devices
print(sys.getsizeof(FileSystem))
# 减少内存后
class FileSystem(object):
__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folder = folders
self.devices = devices
print(sys.getsizeof(FileSystem))
1016
888
26、用lambda 来模仿输出方法
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
python tips 1000 1001
27、从两个相关序列构建一个字典
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
{1: 10, 2: 20, 3: 30}
28、搜索字符串的多个前后缀
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
True
True
29、不使用循环构造一个列表
import itertools import numpy as np test = [[-1, -2], [30, 40], [25, 35]] print(list(itertools.chain.from_iterable(test))) [-1, -2, 30, 40, 25, 35]
30、实现switch-case语句
def xswitch(x):
return xswitch._system_dict.get(x, None)
xswitch._system_dict = {"files":10, "folders":5, "devices":2}
print(xswitch("default"))
print(xswitch("devices"))
None
2
python的30个编程技巧的更多相关文章
- Python初学者的一些编程技巧
#####################喜欢就多多关注哦######################### Python初学者的一些编程技巧 交换变量 ? 1 2 3 4 5 6 7 8 9 ...
- python实用30个小技巧
python实用30个小技巧 展开1.原地交换两个数字Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例: In [1]: x,y = 10 ,20 In [2]: ...
- 给Python初学者的一些编程技巧
展开这篇文章主要介绍了给Python初学者的一些编程技巧,皆是基于基础的一些编程习惯建议,需要的朋友可以参考下交换变量 x = 6y = 5 x, y = y, x print x>>&g ...
- [转]Python程序员必须知道的30条编程技巧
30 tips & tricks for Python Programming 1 直接交换两个数字位置 x, y = 10, 20 print(x, y) x, y = y, x prin ...
- Python的22个编程技巧,请收下!
1. 原地交换两个数字 Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例: x,y= 10,20 print(x,y) x,y= y,x print(x,y) # ...
- python 的一些高级编程技巧
正文: 本文展示一些高级的Python设计结构和它们的使用方法.在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求.对数据一致性的要求或是对索引的要求等,同时也可以将各种数据结构合 ...
- 18个Python高效编程技巧,Mark!
初识Python语言,觉得python满足了我上学时候对编程语言的所有要求.python语言的高效编程技巧让我们这些大学曾经苦逼学了四年c或者c++的人,兴奋的不行不行的,终于解脱了.高级语言,如果做 ...
- Python高效编程技巧实战 实战编程+面试典型问题 中高阶程序员过渡
下载链接:https://www.yinxiangit.com/603.html 目录: 如果你想用python从事多个领域的开发工作,且有一些python基础, 想进一步提高python应用能力 ...
- Python 高效编程技巧实战(2-1)如何在列表,字典, 集合中根据条件筛选数据
Python 高效编程技巧实战(2-1)如何在列表,字典, 集合中根据条件筛选数据 学习目标 1.学会使用 filter 借助 Lambda 表达式过滤列表.集合.元组中的元素: 2.学会使用列表解析 ...
随机推荐
- 404 Note Found 队-Alpha4
目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:丹丹 组员7:何家伟 组员8:政演 组员9:鸿杰 组员10:刘一好 组员:何宇恒 展示组内最新 ...
- ASP.NET MVC 自动模型验证
经常看到这个代码 在controller 中写入验证模型,每个需要验证的action 都写-.. ,就问你烦不烦~ 可以利用 ASP.NET MVC 的 action 拦截机制 自动处理. 1 新建验 ...
- CCF认证201803-1 跳一跳
import java.util.Scanner; public class Jump { public static void main(String[] args) { Scanner sc = ...
- 关于如何解决bootstrap table 列 切换 刷新 高度不一样
在使用bootstrap table时候,碰到bootstrap table 列 切换 刷新 高度不一样的问题,如图所示: 解决这个问题很简单,在你的页头加一句<!DOCTYPE html> ...
- 在 Oracle Linux 6.5 上安装 Oracle 11g 单实例数据库
Checking the Hardware Requirements 系统必须满足下面最小的硬件要求 Memory Requirements Minimum: 1 GB of RAMRecommend ...
- 点击底部input输入框,弹出的软键盘挡住input(苹果手机使用第三方输入法 )
测试移动端页面的时候,偶然发现点击底部input输入框时,弹出的虚拟键盘偶尔会挡住input输入框. 输入框固定在页面底部,如图所示: input固定底部设计图.png 点击底部input输入框唤 ...
- 腾讯云的对象存储COS
什么是对象存储COS Clound Object Storage,COS,专门为企业和开发者们提供能够存储海量的分布式存储服务,用户可以随时通过互联网对大量数据进行批量存储和处理,在任意位置存储和检索 ...
- Redis的特性以及优势(附官网)
NoSQL:一类新出现的数据库(not only sql) 泛指非关系型的数据库 不支持SQL语法 存储结构跟传统关系型数据库中的那种关系表完全不同,nosql中存储的数据都是KV形式 NoSQL的世 ...
- hive工作记录-20180513
Hive的数据导入: 1.从本地文件系统中导入数据到Hive表 基础语法1 : create table 表名(列名1 数据类型, 列名2 数据类型, … …) row format delimite ...
- python多进程详解和协程
1.由于python多线程适合于多IO操作,但不适合于cpu计算型工作,这时候可以通过多进程实现.python多进程简单实用 # 多进程,可以cpu保持一致,python多线程适合多io.对于高cpu ...