pythonmapdel_Python的30个技巧

从公众号上看到了一篇文章《30个python编程技巧!》,觉得有些挺有用的,有的也一直在用,就挨个实现了一下。

1.原地交换两个数字

x, y =10, 20print(x, y)y, x = x, yprint(x, y)1

2

3

4

10 20

20 10

2.链状比较操作符n = 10print(1 < n < 20)print(1 > n <= 9)1

2

3

True

False

3.使用三元操作符来实现条件赋值

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

y = 20x = 9 if (y == 10) else 8print(x)1

2

3

8

4.找abc中最小的数def small(a, b, c):return a if a

2

3

4

5

6

0

1

3

3

5.列表推导

x = [m**2 if m>10 else m**4 for m in range(50)]print(x)1

2[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)1

2

select * from multi_row where row_id < 5multistr = '''select * from multi_row where row_id < 5'''print(multistr)1

2

3

select * from multi_row

where row_id < 5

multistr = ('select * from multi_row''where row_id < 5''order by age')print(multistr)1

2

3

4

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

1 2 3

6.打印引入模块的绝对路径

import threadingimport socketprint(threading)print(socket)1

2

3

4

7.交互环境下的“_”操作符

在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”

8.字典/集合推导testDic = {i: i * i for i in range(10)}testSet = {i * 2 for i in range(10)}print(testDic)print(testSet)1

2

3

4

{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 pdbpdb.ste_trace()1

2

10.开启文件分享

python允许开启一个HTTP服务器从根目录共享文件python -m http.server1

11.检查python中的对象

test = [1, 3, 5, 7]print(dir(test))1

2

[‘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))1

2

[‘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 valuesif m in [1, 2, 3, 4]:# do not use following wayif m==1 or m==2 or m==3 or m==4:1

2

3

4

13.运行时检测python版本import sysif 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)1

2

3

4

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))1

2

3

[‘I’, ‘Like’, ‘Python’]

ILikePython

15.四种翻转字符串、列表的方式# 翻转列表本身testList = [1, 3, 5]testList.reverse()print(testList)1

2

3

4

[5, 3, 1]

# 在一个循环中翻转并迭代输出for element in reversed([1, 3, 5]): print(element)1

2

3

5

3

1# 翻转字符串print('Test Python'[::-1])1

2

nohtyP tseT

# 用切片翻转列表print([1, 3, 5][::-1])1

2

[5, 3, 1]

16.用枚举在循环中找到索引test = [10, 20, 30]for i, value in enumerate(test):print(i, ':', value)1

2

3

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)1

2

3

4

5

6

0

1

2

3

18.从方法中返回多个值def x():return 1, 2, 3, 4a, b, c, d = x()print(a, b, c, d)1

2

3

4

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)1

2

3

4

5

6

7

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))1

2

3

4

5

6

12

6

21.计算任何数的阶乘

import functoolsresult = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)print(result)1

2

3

6

22.找到列表中出现次数最多的数test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]print(max(set(test), key=test.count))1

2

4

23.重置递归限制

python限制递归次数到1000,可以用下面方法重置

import sysx = 1200print(sys.getrecursionlimit())sys.setrecursionlimit(x)print(sys.getrecursionlimit())1

2

3

4

5

1000

1200

24.检查一个对象的内存使用import sysx = 1print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节1

2

3

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))1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1016

888

26.用lambda 来模仿输出方法import syslprint = lambda *args: sys.stdout.write(' '.join(map(str, args)))lprint('python', 'tips', 1000, 1001)1

2

3

python tips 1000 1001

27.从两个相关序列构建一个字典

t1 = (1, 2, 3)t2 = (10, 20, 30)print(dict(zip(t1, t2)))1

2

3

{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')))1

2

True

True

29.不使用循环构造一个列表

import itertoolsimport numpy as nptest = [[-1, -2], [30, 40], [25, 35]]print(list(itertools.chain.from_iterable(test)))1

2

3

4

[-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'))1

2

3

4

5

None

2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值