1.函數式編程
理論就來自lambda演算,雖然沒有學過lisp,一直被其大名震撼。 html
特性: jquery
函數是以一等公民 express
能夠做爲參數 編程
能夠做爲返回值 緩存
具備閉包特性 多線程
1.1參數傳遞方式
- 通常參數傳遞:值傳遞,引用傳遞
- 命名參數傳遞,使用"參數名=值"的格式,Python內成爲關鍵字參數(keyword argument)
- 默認參數設置
- 可變參數,使用*開頭,被解析成爲一個元組
- 可變參數,使用**開頭,被解析成爲一個字典,必須使用關鍵字參數的方式
- 在調用的時候如何加上*,則會被解成元組或字典
-
def func(*args):
-
print type(args)
-
print args
-
-
func(1,2.3,'true')
-
-
def funcDict(**args):
-
print type(args)
-
print args
-
print args['name']
-
-
funcDict(name='pzdn',age=20)
1.2迭代器Iterator
相似C#的枚舉器Enumerator 閉包
-
lst =range(2)
-
it = iter(lst)
-
-
try:
-
while True:
-
print next(it) # it.next()
-
except StopIteration:
-
pass
1.3生成器
生成器就是一種迭代器 框架
- 使用yield關鍵字實現迭代返回
- 和C#的yield是同樣的
- 調用next方法實現迭代
-
def fibonacci():
-
a =b =1
-
yield a
-
yield b
-
while True:
-
a,b = b, a+b
-
yield b
-
-
for num in fibonacci():
-
if num > 100: break
-
print num
1.4 enumerate
enumerate相似jquery的$.each 函數式編程
for idx, ele in enumerate(lst): 函數
print idx, ele
1.5lambda
屬於匿名函數。
- lambda args: expression。第一個是關鍵字,第二個是逗號分隔的參數,冒號以後是表達式塊
1.6map
print map(lambda x:x**3,range(1,6))
print map(lambda x:x+x,'abcde')
print map(lambda x,y:x+y,range(8),range(8))
1.7filter
- 相似Linq的Where擴展方法,選擇爲true的進行計算
print filter(lambda x:x%2 != 0 and x%3 != 0,range(2,20))
1.8reduce
官方解釋:
-
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.
-
def reduce(function, iterable, initializer=None):
-
it = iter(iterable)
-
if initializer is None:
-
try:
-
initializer = next(it)
-
except StopIteration:
-
raise TypeError('reduce() of empty sequence with no initial value')
-
accum_value = initializer
-
for x in iterable:
-
accum_value = function(accum_value, x)
-
return accum_value
-
def statistics(dic,k):
-
if not k in dic:
-
dic[k] = 1
-
else:
-
dic[k] +=1
-
return dic
-
-
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
-
print reduce(statistics,lst,{})
-
#提供第三個參數,第一次,初始字典爲空,做爲statistics的第一個參數,而後遍歷lst,做爲第二個參數,而後將返回的字典集合做爲下一次的第一個參數
print reduce(lambda x,y:x+y,range(1,101)) #5050
print reduce(lambda x,y:x+y,range(1,101),20) #5070
1.9閉包
2.多線程
2.1簡單使用
threading.currentThread()
threading.enumerate()
thread.start_new_thread()
-
import thread,threading
-
import time
-
-
def print_time(threadName, delay):
-
count =0
-
while count < 5:
-
time.sleep(delay)
-
count +=1
-
print "%s %s" % (threadName,time.ctime(time.time()))
-
print threading.currentThread().getName()
-
-
try:
-
thread.start_new_thread(print_time,("T1",4))
-
thread.start_new_thread(print_time,("T2",2))
-
-
except:
-
print "Error: unable to start thread"
-
-
print threading.enumerate()
-
while 1:
-
pass
Thread類
thread.exit()
thread.run()
thread.start()
-
exitFlag =0
-
class myThread(threading.Thread):
-
def __init__(self,threadID,name,counter):
-
threading.Thread.__init__(self)
-
self.threadID = threadID
-
self.name = name
-
self.counter = counter
-
def run(self):
-
print "Starting " + self.name
-
print_time(self.name,self.counter,5)
-
print "Exiting " + self.name
-
-
def print_time(threadName, delay, counter):
-
while counter:
-
if exitFlag:
-
thread.exit()
-
time.sleep(delay)
-
print "%s: %s" % (threadName, time.ctime(time.time()))
-
counter -= 1
-
-
thread1 = myThread(1, "Thread-1", 1)
-
thread2 = myThread(2, "Thread-2", 2)
-
-
thread1.start()
-
thread2.start()
-
for t in threads:
t.join()
print "Exiting Main Thread"
2.2線程同步
threading.Lock().acquire()
threading.Lock().release()
3.Jinja模板
http://jinja.pocoo.org/
http://erhuabushuo.is-programmer.com/posts/33926.html
強大的模板處理引擎
- 語句塊使用:{% 語句 %}
- 取值使用:{{ 值 }}
- 控制流程:
{% if title %} {{}} {% else %} {{}} {% endif %} |
{% for post in posts%} {{}} {% endfor %} |
import jinja2
template = jinja2.Template('Hello, {{name}}')
print template.render(name="pzdn")
4.簡單爬蟲框架
urllib:
參考:http://www.cnblogs.com/sysu-blackbear/p/3629420.html
-
urllib.urlopen(url[,data[,proxies]])
打開一個url,返回一個文件對象。而後能夠進行相似文件對象的操做
-
urllib.urlretrieve(url[,filename[,reporthook[,data]]])
將url定位到的html文件下載到你本地的硬盤中。若是不指定filename,則會存爲臨時文件。
urlretrieve()返回一個二元組(filename,mine_hdrs)
-
urllib.urlcleanup()
清除緩存
-
urllib.quote(url)和urllib.quote_plus(url)
url編碼
-
urllib.unquote(url)和urllib.unquote_plus(url)
url解碼
-
urllib.urlencode(query)
對查詢參數編碼
-
import urllib import re def downloadPage(url): h = urllib.urlopen(url) return h.read() def downloadImg(content): pattern = r'src="(.+?\.jpg)" pic_ext' m = re.compile(pattern) urls = re.findall(m, content) for i, url in enumerate(urls): urllib.urlretrieve(url, "%s.jpg" % (i, )) content = downloadPage("http://tieba.baidu.com/p/2460150866") downloadImg(content) |