# python实用技巧

### 1.原地交换两个数字

Python 提供了一个直观的在一行代码中赋值与交换（变量值）的方法，请参见下面的示例：

``````In [1]: x,y = 10 ,20

In [2]: print(x,y)
10 20

In [3]: x, y = y, x

In [4]: print(x,y)
20 10``````

### 2.链状比较操作符

``````In [5]: n = 10
In [6]: result = 1 < n < 20

In [7]: result
Out[7]: True

In [8]: result = 1 > n <= 9

In [9]: result
Out[9]: False``````

### 3.使用三元操作符来进行条件赋值

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

``x = 10  if (y == 9) else  20``

``x = (classA if y == 1  else classB)(param1, param2)``

### 4.多行字符串

``````In [20]: multistr = "select * from multi_row \
...: where row_id < 5"

In [21]: multistr
Out[21]: 'select * from multi_row where row_id < 5'``````

``````In [23]: multistr ="""select * from multi_row
...: where row_id < 5"""

In [24]: multistr
Out[24]: 'select * from multi_row \nwhere row_id < 5'``````

``````In [25]: multistr = ("select * from multi_row "
...: "where row_id < 5 "
...: "order by age")

In [26]: multistr
Out[26]: 'select * from multi_row where row_id < 5 order by age'``````

### 5.存储列表元素到新的变量中

``````In [27]: testlist = [1,2,3]

In [28]: x,y,z = testlist

In [29]: print(x,y,z)
1 2 3``````

### 6.打印引入模块的文件路径

``````In [30]: import threading

In [31]: import socket

In [33]: print(socket)
<module 'socket' from '/usr/local/lib/python3.5/socket.py'>``````

### 7.交互环境下的"_"操作符

``````In [34]: 2 + 3
Out[34]: 5

In [35]: _
Out[35]: 5

In [36]: print(_)
5``````

“_” 是上一个执行的表达式的输出。

### 8.字典/集合推导式

``````In [37]: testDict = {i : i*i for i in range(5)}

In [38]: testSet = { i*2 for i in range(5)}

In [39]: testDict
Out[39]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

In [40]: testSet
Out[40]: {0, 2, 4, 6, 8}``````

### 9.调试脚本

``````import pdb
pdb.set_trace()``````

break 或b 设置断点
continue 或 c 继续执行程序到下一个断点
list 或 l 查看当前行的代码段
step 或 s 进入函数
return 或 r 执行代码直到从当前函数返回
exit 或 q 中止并退出
next 或 n 执行下一行
clear 或 cl 清除断点
p 或 pp 打印变量的值
cl 清除断点
help 帮助

### 10.开启文件分享

Python 允许运行一个 HTTP 服务器来从根路径共享文件，下面是开启服务器的命令：（python3环境）

``python3 -m http.server``

### 11.检查Python中的对象

``````In [41]: test = [1,3,5,7]

In [42]: 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']``````

### 12.简化if语句

``if m in [1,3,5,7]:``

``if m==1  or m==3  or m==5  or m==7:``

### 13.运行时检测Python版本

``````import sys

#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5n")
sys.exit(1)

#Print Python version in a readable format.
print("Current Python version: ", sys.version)``````

python3运行结果：

``````Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

Current Python version:  3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]``````

### 14.组合多个字符串

``````In [44]: test = ['I', 'Like', 'Python', 'automation']

In [45]: ''.join(test)
Out[45]: 'ILikePythonautomation'``````

### 15.四种翻转字符串/列表的方式

``````In [49]: testList = [1, 3, 5]

In [50]: testList.reverse()

In [51]: testList
Out[51]: [5, 3, 1]``````

``````In [52]: for element in reversed([1,3,5]):
...:     print(element)
...:
5
3
1``````

``````In [53]: "Test Python"[::-1]
Out[53]: 'nohtyP tseT'``````

``[1, 3, 5][::-1]``

### 17.在python中使用枚举量

``````In [56]: class Shapes:
...:

In [57]: Shapes.Circle
Out[57]: 0

In [58]: Shapes.Square
Out[58]: 1

In [59]: Shapes.Triangle
Out[59]: 2

Out[60]: 3``````

### 18.从方法中返回多个值

``````In [61]: def x():
...:     return 1,2,3,4
...:

In [62]: a,b,c,d = x()

In [63]: print(a,b,c,d)
1 2 3 4``````

### 19.从两个相关的序列构建一个字典

``````In [92]: t1 = (1,2,3)

In [93]: t2 =(10,20,30)

In [94]: dict(zip(t1,t2))
Out[94]: {1: 10, 2: 20, 3: 30}``````

### 20.将字典拆分为键和值的列表

``````c = {'Bob': 'male', 'Jack': 'male', 'Mary': 'female', 'Tom': 'male'}

keys1 = list(c.keys())#['Bob', 'Jack', 'Tom', 'Mary']
values1 = list(c.values())#['male', 'male', 'male', 'female']``````

### 21.一行代码计算任何数的阶乘

python3环境：

``````In [75]: import functools

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

In [77]: result
Out[77]: 6``````

### 22.找到列表中出现最频繁的数

``````In [82]: test = [1,2,3,4,2,2,3,1,4,4,4]

In [83]: print(max(set(test),key=test.count))
4``````

### 23.重置递归限制

Python 限制递归次数到 1000，我们可以重置这个值：

``````import sys

x=1001
print(sys.getrecursionlimit())

sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

#1-> 1000
#2-> 100``````

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

python2.7：

``````import sys
x=1
print(sys.getsizeof(x))

#-> 24``````

python3：

``````In [86]: import sys

In [87]: x = 1

In [88]: sys.getsizeof(x)
Out[88]: 28``````

### 25.使用slots来减少内存开支

``````import sys
class FileSystem(object):

def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices
print(sys.getsizeof( FileSystem ))

class FileSystem1(object):

__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices

print(sys.getsizeof( FileSystem1 ))
#In Python 3.5
#1-> 1016
#2-> 888``````

### 26.使用lambda来模仿输出方法

``````In [89]: import sys

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

In [91]: lprint("python","tips",1000,1001)
Out[91]: pythontips1000100118``````

### 27.使用字典来存储选择操作

``````In [70]: stdacl = {
...: 'sum':lambda x,y : x + y,
...: 'subtract':lambda x,y : x - y
...: }

In [73]: stdacl['sum'](9,3)
Out[73]: 12

In [74]: stdacl['subtract'](9,3)
Out[74]: 6``````

### 28.一行代码搜索字符串的多个前后缀

``````In [95]: print("http://www.google.com".startswith(("http://", "https://")))
True

True``````

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

``````In [101]: test = [[-1, -2], [30, 40], [25, 35]]

In [102]: import itertools

In [103]: print(list(itertools.chain.from_iterable(test)))
[-1, -2, 30, 40, 25, 35]``````

### 30.在Python中实现一个真正的switch-case语句

``````In [104]: def xswitch(x):
...:     return xswitch._system_dict.get(x, None)
...:

In [105]: xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}

In [106]: print(xswitch('default'))
None

In [107]: print(xswitch('devices'))
2``````

### 31.计数时使用Counter计数对象

Python的collections类库里有个内置的dict类的子类，是专门来干这种事情的：

``````>>> from collections import Counter
>>> c = Counter( hello world )

>>> c
Counter({ l : 3, o : 2, : 1, e : 1, d : 1, h : 1, r : 1, w : 1})

>>> c.most_common(2)
[( l , 3), ( o , 2)]``````

### 32.漂亮的打印出JSON

JSON是一种非常好的数据序列化的形式，被如今的各种API和web service大量的使用。使用python内置的json处理，可以使JSON串具有一定的可读性，但当遇到大型数据时，它表现成一个很长的、连续的一行时，人的肉眼就很难观看了。

``````>>> import json

>>> print(json.dumps(data))  # No indention
{"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]}

>>> print(json.dumps(data, indent=2))  # With indention

{
"status": "OK",
"count": 2,
"results": [
{
"age": 27,
"name": "Oz",
"lactose_intolerant": true
},
{
"age": 29,
"name": "Joe",
"lactose_intolerant": false
}
]
}``````

27 人关注
40 篇文章