python tips

python tips

來自專欄深度學堂

簡易http伺服器

這個是我覺得最為神奇的,所以放在第一個寫

# Python 2# 在命令行中輸入~ python -m SimpleHTTPServer # 註:複製的時候不要把~加上。。。# Python 3~ python -m http.server# 對了,如果不想用默認埠,在後面添加就行,比如 `python -m SimpleHTTPServer 80` 這樣子Serving HTTP on 0.0.0.0 port 8000 ...

這樣你就能夠很方便的在區域網內交換文件了 (如果出問題我猜可能是防火牆,埠沒有開放的原因)

比如我的ip為172.20.19.221 ,那麼只要是區域網內的人,只要登錄172.20.19.221:8000就能訪問我當前目錄下的所有文件。

比如

點擊任意一個文件瀏覽器就會自動下載,是不是很方便呢,下次同學之間傳文件再也不用u盤了!

man python 查看python命令中-m的意思 -m module-name Searches sys.path for the named module and runs the correspond- ing .py file as a script.其實本質就是導入了-m所接的模塊

map

items = [1, 2, 3, 4, 5]squared = []for i in items: squared.append(i**2)||/items = [1, 2, 3, 4, 5]squared = list(map(lambda x: x**2, items))

list of functions

def multiply(x): return (x*x)def add(x): return (x+x)funcs = [multiply, add]for i in range(5): value = list(map(lambda x: x(i), funcs)) print(value)# Output:# [0, 0]# [1, 2]# [4, 4]# [9, 6]# [16, 8]

filter

number_list = range(-5, 5)less_than_zero = list(filter(lambda x: x < 0, number_list))# 把所有小於0的數字「過濾」出來print(less_than_zero)# Output: [-5, -4, -3, -2, -1]

reduce

product = 1list = [1, 2, 3, 4]for num in list: product = product * num# product = 24 || / /from functools import reduceproduct = reduce((lambda x, y: x * y), [1, 2, 3, 4])# Output: 24

另外,如果你想求一個tuple/set/list/np.array的乘積,除了reduce,還可以使用np.prod函數

>>> import numpy as np...>>> np.prod((2,3))6>>> np.prod([2,3])6>>> np.prod([[2,3],[4,5]],axis=1)array([ 6, 20])

zip

>>>a = [1,2,3]>>> b = [4,5,6]>>> c = [4,5,6,7,8]>>> zipped = zip(a,b) # 打包為元組的列表[(1, 4), (2, 5), (3, 6)]>>> zip(a,c) # 元素個數與最短的列表一致[(1, 4), (2, 5), (3, 6)]>>> zip(*zipped) # 與 zip 相反,可理解為解壓,返回二維矩陣式[(1, 2, 3), (4, 5, 6)]

set

>>> set([2,3,"apple","dog","apple"])set([2, 3, apple, dog])#把重複的元素找出來,你可能會這麼寫↓some_list = [a, b, c, b, d, m, n, n]duplicates = []for value in some_list: if some_list.count(value) > 1: if value not in duplicates: duplicates.append(value)print(duplicates)# Output: [b, n]# 但是用了set就能這麼寫↓some_list = [a, b, c, b, d, m, n, n]duplicates = set([x for x in some_list if some_list.count(x) > 1])print(duplicates)# Output: set([b, n])

求交集

valid = set([yellow, red, blue, green, black])input_set = set([red, brown])print(input_set.difference(valid))# Output: set([brown])

if ... else ...

>>> [x*y for x in range(2,5) for y in range(3,6) if x*y is not 6 ][8, 10, 9, 12, 15, 12, 16, 20]>>> ["apple" if i is 2 else "peach" for i in range(9)][peach, peach, apple, peach, peach, peach, peach, peach, peach]is_fat = Truestate = "fat" if is_fat else "not fat"fat = Truefitness = ("skinny", "fat")[fat]print("Ali is ", fitness)# Output: Ali is fat

Decorators

def hi(name="yasoob"): return "hi " + nameprint(hi())# output: hi yasoob# We can even assign a function to a variable likegreet = hi# We are not using parentheses here because we are not calling the function hi# instead we are just putting it into the greet variable. Lets try to run thisprint(greet())# output: hi yasoob# Lets see what happens if we delete the old hi function!del hiprint(hi())#outputs: NameErrorprint(greet())#outputs: hi yasoob

在函數中定義函數

def hi(name="yasoob"): print("now you are inside the hi() function") def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" print(greet()) print(welcome()) print("now you are back in the hi() function")hi()#output:now you are inside the hi() function# now you are in the greet() function# now you are in the welcome() function# now you are back in the hi() function# This shows that whenever you call hi(), greet() and welcome()# are also called. However the greet() and welcome() functions# are not available outside the hi() function e.g:greet()#outputs: NameError: name greet is not defined

在函數中返回函數

def hi(name="yasoob"): def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" if name == "yasoob": return greet else: return welcomea = hi()print(a)#outputs: <function greet at 0x7f2143c01500>#This clearly shows that `a` now points to the greet() function in hi()#Now try thisprint(a())#outputs: now you are in the greet() function

將函數傳入函數

def hi(): return "hi yasoob!"def doSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func())doSomethingBeforeHi(hi)#outputs:I am doing some boring work before executing hi()# hi yasoob!

Enumerate

for counter, value in enumerate(some_list): print(counter, value)my_list = [apple, banana, grapes, pear]for c, value in enumerate(my_list, 1): print(c, value)# Output:# 1 apple# 2 banana# 3 grapes# 4 pear>>> help(enumerate)enumerate(iterable[, start]) -> iterator for index, value of iterable>>> for i, v in enumerate([888,9999,77]):... print(i,v)...(0, 888)(1, 9999)(2, 77)>>> for i, v in enumerate([888,9999,77],1):... print(i,v)...(1, 888)(2, 9999)(3, 77)>>> for i, v in enumerate([888,9999,77],2):... print(i,v)...(2, 888)(3, 9999)(4, 77)

參考資料

Intermediate Python

推薦閱讀:

這可能是我見過最好的編程指南了!
專欄開啟:記錄自己的編程之路
Arduino編程風格(譯)
c++面向對象編程小實戰(第2篇*下)
0基礎學Python之七:條件語句

TAG:Python | 計算機科學 | 編程 |