30个Python常用小技巧(下篇)

16、用枚举在循环中找到索引

1

2

3

test = [102030]

for i, value in enumerate(test):

    print(i, ':', value)

0 : 10

1 : 20

2 : 30

 

17、定义枚举量

1

2

3

4

5

6

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、从方法中返回多个值

1

2

3

4

def x():

    return 1234

a, b, c, d = x()

print(a, b, c, d)

 

1 2 3 4

 

19、使用*运算符unpack函数参数

1

2

3

4

5

6

7

def test(x, y, z):

    print(x, y, z)

testDic = {'x':1'y':2'z':3}

testList = [102030]

test(*testDic)

test(**testDic)

test(*testList)

z x y

1 2 3

10 20 30

 

20、用字典来存储表达式

1

2

3

4

5

6

stdcalc = {

    "sum"lambda x, y: x + y,

    "subtract"lambda x, y: x - y

}

print(stdcalc["sum"](93))

print(stdcalc["subtract"](93))

12

6

 

21、计算任何数的阶乘

1

2

3

import functools

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

print(result)

6

 

22、找到列表中出现次数最多的数

1

2

test = [123422314444]

print(max(set(test), key=test.count))

4

 

23、重置递归限制

 

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

1

2

3

4

5

import sys

= 1200

print(sys.getrecursionlimit())

sys.setrecursionlimit(x)

print(sys.getrecursionlimit())

 

1000

 

1200

 

24、检查一个对象的内存使用

1

2

3

import sys

= 1

print(sys.getsizeof(x))    # python3.5中一个32比特的整数占用28字节

 

28

 

25、使用slots减少内存开支

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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 来模仿输出方法

1

2

3

import sys

lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))

lprint("python""tips"10001001)

 

python tips 1000 1001

 

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

1

2

3

t1 = (123)

t2 = (102030)

print(dict(zip(t1, t2)))

 

{1: 10, 2: 20, 3: 30}

 

28、搜索字符串的多个前后缀

1

2

print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://""https://")))

print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb"".py")))

True

 

True

 

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

1

2

3

4

import itertools

import numpy as np

test = [[-1-2], [3040], [2535]]

print(list(itertools.chain.from_iterable(test)))

[-1, -2, 30, 40, 25, 35]

 

30、实现switch-case语句

1

2

3

4

5

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值