python的30个编程技巧
python的30个编程技巧
In [1]:
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)
In [3]:
n = 10
print(1 < n < 20)
print(1 > n <= 9)
In [4]:
y = 20
x = 9 if (y == 10) else 8
print(x)
In [6]:
# 找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))
In [7]:
# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]
print(x)
In [15]:
multistr = "select * from multi_row \
where row_id < 5"
print(multistr)
In [16]:
multistr = """select * from multi_row
where row_id < 5"""
print(multistr)
In [17]:
multistr = ("select * from multi_row"
"where row_id < 5"
"order by age")
print(multistr)
In [18]:
testList = [1, 2, 3]
x, y, z = testList # 变量个数应该和列表长度严格一致
print(x, y, z)
In [19]:
import threading
import socket
print(threading)
print(socket)
In [1]:
testDic = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDic)
print(testSet)
In [ ]:
import pdb
pdb.ste_trace()
In [ ]:
python -m http.server
In [3]:
test = [1, 3, 5, 7]
print(dir(test))
In [4]:
test = range(10)
print(dir(test))
In [ ]:
# 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:
In [12]:
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)
In [19]:
test = ["I", "Like", "Python"]
print(test)
print("".join(test))
In [21]:
# 翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
In [23]:
# 在一个循环中翻转并迭代输出
for element in reversed([1, 3, 5]):
print(element)
In [24]:
# 翻转字符串
print("Test Python"[::-1])
In [25]:
# 用切片翻转列表
print([1, 3, 5][::-1])
In [26]:
test = [10, 20, 30]
for i, value in enumerate(test):
print(i, ':', value)
In [27]:
class shapes:
circle, square, triangle, quadrangle = range(4)
print(shapes.circle)
print(shapes.square)
print(shapes.triangle)
print(shapes.quadrangle)
In [28]:
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
In [35]:
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)
In [37]:
stdcalc = {
"sum": lambda x, y: x + y,
"subtract": lambda x, y: x - y
}
print(stdcalc["sum"](9, 3))
print(stdcalc["subtract"](9, 3))
In [38]:
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
In [40]:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 4]
print(max(set(test), key=test.count))
In [41]:
import sys
x = 1200
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
In [42]:
import sys
x = 1
print(sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节
In [47]:
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))
In [49]:
import sys
lprint = lambda *args: sys.stdout.write(" ".join(map(str, args)))
lprint("python", "tips", 1000, 1001)
In [50]:
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2)))
In [52]:
print("http://localhost:8888/notebooks/Untitled6.ipynb".startswith(("http://", "https://")))
print("http://localhost:8888/notebooks/Untitled6.ipynb".endswith((".ipynb", ".py")))
In [55]:
import itertools
import numpy as np
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
In [58]:
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"))