python30个小技巧

转载:https://www.pythontab.com/html/2018/pythonjichu_0917/1351.html
编程中用到可以简化代码的30个小技巧,当然python的技巧远不止这些,让我们在学习的途中去发现宝藏吧。
推荐一个python网站取了一定有惊喜python中文开发者社区门户

  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

  1. 使用三元操作符来实现条件赋值
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]
  1. 多行字符串
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
  1. 存储列表元素到新的变量
testList = [1, 2, 3]
x, y, z = testList    # 变量个数应该和列表长度严格一致
print(x, y, z)
1 2 3 
  1. 打印引入模块的绝对路径
import threading
import socket
print(threading)
print(socket)
<module 'threading' from 'd:\\python351\\lib\\threading.py'>
<module 'socket' from 'd:\\python351\\lib\\socket.py'>
  1. 交互环境下的“_”操作符

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

  2. 字典/集合推导

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}

  1. 调试脚本

    用pdb模块设置断点

import pdb
pdb.ste_trace()
  1. 开启文件分享

    python允许开启一个HTTP服务器从根目录共享文件

```
python -m http.server
```
  1. 检查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'] 
  1. 简化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:
```
  1. 运行时检测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)]
  1. 组合多个字符串
```
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
```

['I', 'Like', 'Python']



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

0 : 10

1 : 20

2 : 30
  1. 定义枚举量
```
class shapes:
    circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
```

0

1

2

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

 1 2 3 4 
  1. 使用*运算符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
  1. 用字典来存储表达式
```
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
  1. 计算任何数的阶乘
```
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
```

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

4
  1. 重置递归限制

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

```
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
```

1000



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

28
  1. 使用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
  1. 用lambda 来模仿输出方法
```
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
```

 python tips 1000 1001 
  1. 从两个相关序列构建一个字典
```
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
```

 {1: 10, 2: 20, 3: 30} 
  1. 搜索字符串的多个前后缀
```
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
```

True



True
  1. 不使用循环构造一个列表
```
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] 
  1. 实现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 

5
  1. 拼接字符串的7种方法

    1. 直接通过(+)操作符拼接
    s = 'Hello'+' '+'World'+'!'
    print(s)
    
    1. 通过str.join()方法拼接
    strlist=['Hello',' ','World','!']
    print(''.join(strlist))
    
    1. 通过str.format()方法拼接
    s='{} {}!'.format('Hello','World')
    print(s)
    
    1. 通过(%)操作符拼接
    s = '%s %s!' % ('Hello', 'World')
    print(s)
    
    1. 通过()多行拼接
    s = (
        'Hello'
        ' '
        'World'
        '!'
    )
    print(s)
    
    1. 通过string模块中的Template对象拼接
    from string import Template
    s = Template('${s1} ${s2}!') 
    print(s.safe_substitute(s1='Hello',s2='World'))
    

    输出结果:Hello World!

    Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这种方式的好处是不需要担心参数不一致引发异常,如:

    from string import Template
    s = Template('${s1} ${s2} ${s3}!') 
    print(s.safe_substitute(s1='Hello',s2='World'))
    

    输出结果:Hello World ${s3}!

    1. 通过F-strings拼接

      在python3.6.2版本中,PEP 498 提出一种新型字符串格式化机制,被称为“字符串插值”或者更常见的一种称呼是F-strings,F-strings提供了一种明确且方便的方式将python表达式嵌入到字符串中来进行格式化:

      s1='Hello'
      s2='World'
      print(f'{s1} {s2}!')
      

      输出结果:Hello World!

      在F-strings中我们也可以执行函数:

      def power(x):
          return x*x
      x=4
      print(f'{x} * {x} = {power(x)}')
      

      输出结果:4 * 4 = 16

      而且F-strings的运行速度很快,比%-string和str.format()这两种格式化方法都快得多。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值