从公众号上看到了一篇文章《30个python编程技巧!》,觉得有些挺有用的,有的也一直在用,就挨个实现了一下。
1、原地交换两个数字
In [1]:
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
2、链状比较操作符
In [3]:
n = 10
print(1 < n < 20)
print(1 > n <= 9)
3、使用三元操作符来实现条件赋值
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
In [4]:
y = 20
x = 9 if (y == 10) else 8
print(x)
In [6]:
# 找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))
In [7]:
# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)
4、多行字符串
In [15]:
multistr = "select * from multi_row
where row_id < 5"
print(multistr)
In [16]:
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)
In [17]:
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
5、存储列表元素到新的变量
In [18]:
testList = [1, 2, 3]
x, y, z = testList # 变量个数应该和列表长度严格一致
print(x, y, z)
6、打印引入模块的绝对路径
In [19]:
import threading
import socket
print(threading)
print(socket)
7、交互环境下的“_”操作符
在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
8、字典/集合推导
In [1]:
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
9、调试脚本
用pdb模块设置断点
In [ ]:
import pdb
pdb.ste_trace()
10、开启文件分享
python允许开启一个HTTP服务器从根目录共享文件
In [ ]:
python -m http.server
11、检查python中的对象
In [3]:
test = [1, 3, 5, 7]
print(dir(test))
In [4]:
test = range(10)
print(dir(test))
12、简化if语句
In [ ]:
# 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版本
In [12]:
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)
14、组合多个字符串
In [19]:
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
15、四种翻转字符串、列表的方式
In [21]:
# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
In [23]:
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
print(element)
In [24]:
# 翻转字符串
print("Test Python"[::-1])
In [25]:
# 用切片翻转列表
print([1, 3, 5][::-1])
16、用枚举在循环中找到索引
In [26]:
test = [10, 20, 30]
for i, value in enumerate(test):
print(i, ':', value)
17、定义枚举量
In [27]:
class shapes:
circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
18、从方法中返回多个值
In [28]:
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
19、使用*运算符unpack函数参数
In [35]:
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)
20、用字典来存储表达式
In [37]:
stdcalc = {
"sum": lambda x, y: x + y,
"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
21、计算任何数的阶乘
In [38]:
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
22、找到列表中出现次数最多的数
In [40]:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
23、重置递归限制
python限制递归次数到1000,可以用下面方法重置
In [41]:
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
24、检查一个对象的内存使用
In [42]:
import sys
x = 1
print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节
25、使用slots减少内存开支
In [47]:
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))
26、用lambda 来模仿输出方法
In [49]:
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
27、从两个相关序列构建一个字典
In [50]:
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
28、搜索字符串的多个前后缀
In [52]:
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
29、不使用循环构造一个列表
In [55]:
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
30、实现switch-case语句
In [58]:
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"))