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控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”

>>> 1+1

2

>>> _

2

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.set_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、四种翻转字符串、列表的方式

# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList) 
[5, 3, 1]
 
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
print(element)
5
3
1
 
# 翻转字符串
print("Test Python"[::-1])
nohtyP tseT
 
# 用切片翻转列表
print([1, 3, 5][::-1])
[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

31、简化导入模块名

from bs4 import BeautifulSoup as BS
html = '''...'''
soup = BS(html,"html.parser")

32、在一行中捕获多个异常

try:
  pass
except (ExceptionA,ExceptionB,……) as e:
  pass

33、查找列表中某个元素的下标

>>>a = ["a","b","c","d","e","f"]
>>>a.index("b")
>>> 1

34、包管理

Python世界最棒的地方之一,就是大量的第三方程序包。同样,管理这些包也非常容易。按照惯例,会在 requirements.txt 文件中列出项目所需要的包。每个包占一行,通常还包含版本号。

  1. pelican==3.3
  2. Markdown
  3. pelican-extended-sitemap==1.0.0

35、名称前的单下划线(如:_shahriar)

程序员使用名称前的单下划线,用于指定该名称属性为“私有”。这有点类似于惯例,为了使其他人(或你自己)使用这些代码时将会知道以“_”开头的名称只供内部使用。正如Python文档中所述:

以下划线 __ 为前缀的名称(如_pam)应该被视为API中非公开的部分(不管是函数、方法还是数据成员)。此时,应该将它们看作是一种实现细节,在修改它们时无需对外部通知。

正如上面所说,这确实类似一种惯例,因为它对解释器来说确实有一定的意义,如果你写了代码 : from <模块/包名> import * ,那么以 _ 开头的名称都不会被导入,除非模块或包中的 __all__ 列表显式地包含了它们。了解更多请查看 Importing * in Python

36、 隐藏特性 --- print 重定向输出到文件

注意打开的模式: “w+” 而不能 “w” , 当然 “a” 是可以的

>>> print >> open("somefile", "w+")

37、隐藏特性 --- isinstance可以接收一个元组

这个真的鲜为人知, 我们可以用 isinstance(x, (float, int)) 来判断 x 是不是数,也就是那个元组里面是 或 的关系,只要是其中一个的实例就返回 True。

>>> isinstance(1, (float, int))

True

>>> isinstance(1.3, (float, int))

True

>>> isinstance("1.3", (float, int))

False

python 37条编程技巧-汇总(转载+整理)的更多相关文章

  1. [转]Python程序员必须知道的30条编程技巧

    30 tips & tricks for Python Programming 1  直接交换两个数字位置 x, y = 10, 20 print(x, y) x, y = y, x prin ...

  2. 【JMeter】教程及技巧汇总(转载)

    转载地址:http://www.hissummer.com/jmeter-summary.html 参考/学习资料:http://www.yiibai.com/jmeter/jmeter_build_ ...

  3. Python 学习笔记 编程基础汇总000

    编程基础知识汇总000 1.计算机结构 2.编程语言分类 3.字符编码由来 计算机结构 计算机组成五大部件: 控制器.运算器.存储器.输入.输出 控制器(Controler):对程序规定的控制信息进行 ...

  4. 18个python的高效编程技巧

    01 交换变量 >>>a=3 >>>b=6 这个情况如果要交换变量在c++中,肯定需要一个空变量.但是python不需要,只需一行,大家看清楚了 >>& ...

  5. 编程中遇到的Python错误和解决方法汇总整理

    这篇文章主要介绍了自己编程中遇到的Python错误和解决方法汇总整理,本文收集整理了较多的案例,需要的朋友可以参考下   开个贴,用于记录平时经常碰到的Python的错误同时对导致错误的原因进行分析, ...

  6. 偏执却管用的10条Java编程技巧

    本文由 ImportNew - LynnShaw 翻译自 javacodegeeks.欢迎加入翻译小组.转载请见文末要求. 经过一段时间的编码(咦,我已经经历了将近20年的编程生涯,快乐的日子总是过得 ...

  7. 关于Python的10大实用编程技巧

      Python 是一种通用的脚本开发语言,比其他编程语言更加简单.易学,其面向对象特性甚至比Java.C#..NET更加彻底,因此非常适合快速开发. Python 已经成为最受欢迎的程序设计语言之一 ...

  8. 给Python初学者的一些编程技巧

    展开这篇文章主要介绍了给Python初学者的一些编程技巧,皆是基于基础的一些编程习惯建议,需要的朋友可以参考下交换变量 x = 6y = 5 x, y = y, x print x>>&g ...

  9. 18个Python高效编程技巧,Mark!

    初识Python语言,觉得python满足了我上学时候对编程语言的所有要求.python语言的高效编程技巧让我们这些大学曾经苦逼学了四年c或者c++的人,兴奋的不行不行的,终于解脱了.高级语言,如果做 ...

随机推荐

  1. 如何使用eclipse for c/c++ 配置环境编写第一个C程序

    因为VS太大还要安装太多的插件,,,所以想用eclipse编写C语言... 1.下载eclipse for c/c++版本  去官网即可下载   https://www.eclipse.org/dow ...

  2. 中间件序列TDATASET为BUFFER演示代码

    procedure SendStream(const AStream: TStream);var Buffer: array[0..4095] of Byte; // 每包最大4K StartPos, ...

  3. (转)Delphi2009初体验 - 语言篇 - 智能指针(Smart Pointer)的实现

     转载:http://www.cnblogs.com/felixYeou/archive/2008/08/27/1277250.html 快速导航 一. 回顾历史二. 智能指针简介三. Delphi中 ...

  4. [PythonCode]扫描局域网的alive ip地址

    内网的主机都是自己主动分配ip地址,有时候须要查看下有那些ip在使用,就写了个简单的脚本. linux和windows下都能够用,用多线程来ping1-255全部的地址,效率不高.2分钟左右. 先凑合 ...

  5. 如何离线分析Kafka海量业务消息?1分钟快速为您支招

    场景介绍 说起Kafka,许多使用者对它是又爱又恨.Kafka是一种分布式的.基于发布/订阅的消息系统,其极致体验让人欲罢不能,但操心的运维.复杂的安全策略.可靠性易用性的缺失等,仍需要使用者付出诸多 ...

  6. Android lowmemorykiller

    drivers/staging/android/lowmemorykiller.c lowmemorykiller 在系统空闲内存不足时, 根据一定机制选择某个进程, 然后杀死它. 1. regist ...

  7. 树莓派的PWM脉宽调制功能介绍

    近期想用树莓派控制航模的电调,于是研究了下PWM.貌似控制电调比較麻烦,由于电调须要发送几个特定的信号启动,然后才干进入控制模式.今天先弄明确PWM,慢慢折腾.以下的程序亲測可用,我用的树莓派mode ...

  8. 【MongoDB】The description of procedure in MongoDB

    In this blog the procedure of mongodb will be described in details. It is known that mongodb has pro ...

  9. 【翻译自mos文章】在12c中Create or Truncate Table时非常慢,等待事件为 DFS Lock Handle wait

    来源于: Create or Truncate Table Slow in 12c While Waiting for DFS Lock Handle wait (文档 ID 2085308.1) A ...

  10. 2016/3/27 PHP中include和require的区别详解

    1.概要 require()语句的性能与include()相类似,都是包括并运行指定文件.不同之处在于:对include()语句来说,在执行文件时每次都要进行读取和评估:而对于require()来说, ...