原地交換兩個數字
1.x, y =
2.print(x, y)
3.y, x = x, y
4.print(x, y)
10 20
20 10
如果你感覺學不會?莫慌,小編準備了一份學習資料,
鏈狀比較操作符
1.n = 10
2.print(1 < n < 20)
3.print(1 > n <= 9)
True
False
如果你感覺學不會?莫慌,小編準備了一份學習資料,
使用三元操作符來實現條件賦值
[表達式為真的返回值] if [表達式] else [表達式為假的返回值]
1.y = 20
2.x = 9 if (y == 10) else 8
3.print(x)
8
# 找abc中最小的數
1.def small(a, b, c):
2. return a if a
3·print(small(1, 0, 1))
4·print(small(1, 2, 2))
5·print(small(2, 2, 3))
6·print(small(5, 4, 3))
0
1
3
3
1·# 列表推導
2·x = [m**2 if m>10 else m**4 for m in range(50)]
3·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 \
2·where row_id < 5"
3·print(multistr)
4·select * from multi_row where row_id < 5
5·multistr = """select * from multi_row
6·where row_id < 5"""
7·print(multistr)
8·select * from multi_row
9·where row_id < 5
10·= ("select * from multi_row"
11·"where row_id < 5"
12·"order by age")
13·print(multistr)
14·select * from multi_rowwhere row_id < 5order by age
存儲列表元素到新的變量
1·testList = [1, 2, 3]
2·x, y, z = testList # 變量個數應該和列表長度嚴格一致
3·print(x, y, z)
1 2 3
如果你感覺學不會?莫慌,小編準備了一份學習資料,
打印引入模塊的絕對路徑
1·import threading
2·import socket
3·print(threading)
4·print
5·<module>from 'd:\\python351\\lib\\threading.py'>/<module>
6·<module>from 'd:\\python351\\lib\\socket.py'>/<module>
交互環境下的“_”操作符
在python控制檯,不論我們測試一個表達式還是調用一個方法,結果都會分配給一個臨時變量“_”
字典/集合推導
1·testDic = {i: i * i for i in range(10)}
2·testSet = {i * 2 for i in range(10)}
3·print(testDic)
4·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}
調試腳本
用pdb模塊設置斷點
1·import pdb
2·pdb.ste_trace()
開啟文件分享
python允許開啟一個HTTP服務器從根目錄共享文件
1
python -m http.server
檢查python中的對象
1·test = [1, 3, 5, 7]
2·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·test = range(10)
2·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']
簡化if語句
1·# use following way to verify multi values
2·if m in [1, 2, 3, 4]:
3·# do not use following way
4·if m==1 or m==2 or m==3 or m==4:
運行時檢測python版本
1·import sys
2·if not hasattr(sys, "hexversion") or sys.version_info != (2, 7):
3· print("sorry, you are not running on python 2.7")
print("current python version:", sys.version)
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)]
組合多個字符串
1·test = ["I", "Like", "Python"]
2·print(test)
3·print("".join(test))
['I', 'Like', 'Python']
ILikePython
如果你感覺學不會?莫慌,小編準備了一份學習資料,
四種翻轉字符串、列表的方式
5
3
1
用枚舉在循環中找到索引
1·test = [10, 20, 30]
2·for i, value in
3· print(i, ':', value)
0 : 10
1 : 20
2 : 30
定義枚舉量
1·class shapes:
2· circle, square, triangle, quadrangle = range(4)
3·print(shapes.circle)
4·print(shapes.square)
5·print(shapes.triangle)
6·print(shapes.quadrangle)
0
1
2
3
從方法中返回多個值
1·def x():
2· return 1, 2, 3, 4
3·a, b, c, d
4·print(a, b, c, d)
1 2 3 4
如果你感覺學不會?莫慌,小編準備了一份學習資料,
使用*運算符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 = [10, 20, 30]
test(*testDic)
test(**testDic)
test(*testList)
z x y
1 2 3
10 20 30
用字典來存儲表達式
1
2
3
4
5
6
stdcalc = {
"sum": lambda x, y: x + y,
"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
12
計算任何數的階乘
1
2
3
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
6
找到列表中出現次數最多的數
1
2
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
4
重置遞歸限制
python限制遞歸次數到1000,可以用下面方法重置
1
2
3
4
5
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
1000
1200
檢查一個對象的內存使用
1
2
3
import sys
x = 1
print(sys.getsizeof(x)) # python3.5中一個32比特的整數佔用28字節
使用slots減少內存開支
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import sys
# 原始類
class
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
1016
888
用lambda 來模仿輸出方法
1
2
3
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
python tips 1000 1001
從兩個相關序列構建一個字典
1
2
3
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
{1: 10, 2: 20, 3: 30}
搜索字符串的多個前後綴
1
2
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
True
True
不使用循環構造一個列表
1
2
3
4
import itertools
import numpy as np
test
print(list(itertools.chain.from_iterable(test)))
[-1, -2, 30, 40, 25, 35]
實現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"))