Python學習筆記

因在面試的時候會一門腳本語言是有很大優勢的,所以今天華爲機試回來愉快的決定將Python納入複習計劃之中,先學習重要的語法,然後和波波討論寫個簡單的服務器,如果來得及的話,就實現個搜索引擎,最後,每次刷題時,嘗試用Python,我的windows編譯器版本是2.7.7。參考書是《Python基礎教程(第2版)》Hetland,

大致將基礎看完,然後結合例子練一練。

2014年8月15日23:24:04:看了前5章,是很基礎的,下面再看一遍,嘗試用Python刷題。

加油,


更新:2014年11月29日

最近看了http://www.liaoxuefeng.com/的博客,裏面的例子很好,很適合外行快速入門,不需要深入瞭解他,只需要知道他是什麼就可以了。

看到 裝飾器 了(這個總體還是比較有用的,自己多看看,下次接着看吧)


當Python解釋器讀取源代碼時,爲了讓他按UTF-8編碼讀取,我們通常在文件開頭寫上這兩行:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


Python裝飾器(decorator)


Web開發 看了一點,沒有看懂。



常見面試題:

1、請教一下列表與元組的區別是什麼.分別在什麼情況下使用?字典呢?

2、Python是如何進行內存管理的?

答:http://blog.chinaunix.net/uid-26602509-id-3506965.html

3、解釋一下python的 and-or 語法

    答:http://www.cnblogs.com/BeginMan/p/3197123.html

4、Python裏面如何拷貝一個對象?

Python中的對象之間賦值時是按引用傳遞的,如果需要拷貝對象,需要使用標準庫中的copy模塊。
1) copy.copy 淺拷貝 只拷貝父對象,不會拷貝對象的內部的子對象。
2) copy.deepcopy 深拷貝 拷貝對象及其子對象

5、如何在一個function裏面設置一個全局的變量?
    答:解決方法是在function的開始插入一個global聲明

6、pass語句什麼也不做,一般作爲佔位符或者創建佔位程序,pass語句不會執行任何操作

7、參數是如何傳遞的?

答:在Python中一切都是對象,任何變量都是對象的引用,你不能改變引用,但是你可以改變可變對象,數字,string, tuple是不可變得,list和dict是可變的。

8、什麼是列表和字典推導(list and dict comprehensions)?你能給個例子嗎?

答:列表字典推導是一種語法糖,用來簡化列表和字典的生成。

# simple iteration
a = []
for x in range(10):
    a.append(x*2)
# a == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# list comprehension
a = [x*2 for x in range(10)]

# dict comprehension
a = {x: x*2 for x in range(10)}
# a == {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18

# set comprehension
a = {x**2 for x in range(10) if x % 2 == 0}
# a == set([0, 16, 4, 64, 36])

9、什麼是PEP8?

答:PEP8定義的是Python代碼規範,告訴你如何書寫可讀性強、更好維護的代碼。

10、你用過虛擬環境嗎?

答:用過,virtualenv用來孤立你的開發和運行環境,特別是當需要同時開發多個項目,基於不同的 Python 版本以及運行庫的時候。

11、如何計算list中元素之和?之積?

# 計算列表內所有元素的和, 包括基本loop方式,sum函數方式,以及使用reduce函數
# the basic way
s = 0
for x in range(10):
    s += x

# the right way
s = sum(range(10))

# the other way
from operator import add
s = reduce(add, range(10))

# 計算列表內所有元素的乘積

# the basic way
s = 1
for x in range(1, 10):
    s = s * x

# the other way
from operator import mul
reduce(mul, range(1, 10)) #ref: http://www.cnblogs.com/dwnblogs/archive/2012/10/26/2741169.html

12、list和tuple的區別,舉例子?

答:list可改變,tuple不可改變,可用作hash值,比如作爲dict的key。

13、range和xrange的區別?

答:1)range返回list對象,而xrange返回xrange對象(大小固定),列表對象已經在內存中存在了,而xrange對象永遠佔 用同樣的內存大小,無論需要生成的range有多大。2)xrange對象不能使用列表對象的切片函數。

14、Python2.x和3.x的區別?

15、什麼是裝飾器(decorator),用法?

答:裝飾器允許你在函數或類中插入和修改代碼,也就是在執行原代碼之前或之後執行程序;

常見用法:記錄某函數調用,權限檢查,

內存緩存:

def memoize(f):
      memo = {}  #  將結果緩存在memo字典對象中,key是參數,value是結果。
      def helper(x):
          if x not in memo:            
              memo[x] = f(x)
          return memo[x]
      return helper

  # 修飾fib函數,任何fib函數的調用,將首先察看是否已經有緩存的結果
  @memoize
  def fib(n):
      if n == 0:
          return 0
      elif n == 1:
          return 1
      else:
          return fib(n-1) + fib(n-2)

  print(fib(40))  #  102334155
參數檢查

def argument_test_natural_number(f):
      def helper(x):
          if type(x) == int and x > 0:
              return f(x)
          else:
              raise Exception("Argument is not an integer")
      return helper

  @argument_test_natural_number
  def faculty(n):
      if n == 1:
          return 1
      else:
          return n * faculty(n-1)

  for i in range(1,10):
      print(i, faculty(i))
  # 1 1
  # 2 2
  # 3 6
  # 4 24
  # 5 120
  # 6 720
  # 7 5040
  # 8 40320
  # 9 362880

  faculty(-1) # 使用非法的參數調用faculty函數,這將raise一個exception
  # Exception: Argument is not an integer

16、Package/Module的定義以及模塊加載原則?

答:模塊就是可重用的代碼段,要告訴解釋器到哪尋找模塊,可增加測試代碼,用__name__判斷是否在“主程序”中(__main__)。

爲了更好的組織模塊,可將它們分組爲包(package)。必須包含__init__py的文件。

17,、什麼是迭代器(iterator)?什麼是Python生成器(generator),如何使用?

答:

1)迭代器對象要求支持迭代器協議,所謂支持迭代器協議就是對象包含__iter__()和next()方法。其中__iter__()方法返回迭代器對象自己;next()方法返回下一個前進到下一個結果,在結尾時引發StopIteration異常。

2)生成器使python可以很容易的支持迭代協議。生成器通過生成器函數產生,生成器函數可以通過常規的def語句來定義,但是不用return返回,而是用yeild一次返回一個結果,在每個結果之間掛起和繼續它們的狀態,來自動實現迭代協議。

參考網頁:

http://ilian.i-n-i.org/python-interview-question-and-answers/

http://xiaocong.github.io/blog/2013/06/16/python-interview-question-and-answer/


下面把 ch2 ch3 ch4這三章好好看看。


第二章:列表和元祖

Python包含6種內建的序列:列表,元祖,字符串,Unicode字符串,buffer對象,xrange對象。

通用序列操作:

1)索引

greeting='Hello'
print greeting[1]

2)分片

numbers=[1,2,3,4,5,6,7,8,9,10]
print numbers[0:10:2]
#[1, 3, 5, 7, 9]

3)序列相加

print [1,2,3]+[4,5,6]
#[1, 2, 3, 4, 5, 6]

4)乘法

print 'Python '*3
#Python Python Python 

5)成員資格

permissions='rw'
print 'w' in permissions
# True

6)長度,最小值,最大值

numbers=[11,21,31]
print len(numbers)
print max(numbers)
print min(numbers)
# 3
# 31
# 11

列表:Python的‘苦力’

1)由字符串創建列表(list函數)

print list('hello')
# ['h', 'e', 'l', 'l', 'o']

列表的基本操作

1)改變列表:元素賦值

>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]
2)刪除元素

>>> names=['zhou','wei']
>>> del names[1]
>>> names
['zhou']
3)分片賦值

>>> name=list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:]=list('haha')
>>> name
['P', 'e', 'h', 'a', 'h', 'a']


列表方法

1)append

>>> lst=[1,2,3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.append('zhou')
>>> lst
[1, 2, 3, 4, 'zhou']
2)count

>>> ['to','be','or','not','to','be'].count('to')
2
>>> 
3)extend

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
4)index

>>> ['to','be','or','not','to','be'].index('or')
2
>>> 
5)insert

>>> numbers=[1,2,3,4,5]
>>> numbers.insert(2,'zhouwei')
>>> numbers
[1, 2, 'zhouwei', 3, 4, 5]
6)pop

>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

7) remove(刪除第一個匹配項)

>>> numbers=['to','be','or','not','to','be']
>>> numbers.remove('to')
>>> numbers
['be', 'or', 'not', 'to', 'be']
>>> 

8)reverse

>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
>>> 

9)sort

>>> x=[4,3,2,1]
>>> x.sort()
>>> x
[1, 2, 3, 4]
>>> 

10) 高級排序

>>> x=['zhouwei','zhou','wei']
>>> x.sort(key=len)
>>> x
['wei', 'zhou', 'zhouwei']
>>> x.sort(reverse=True)
>>> x
['zhouwei', 'zhou', 'wei']
>>> 


元祖:不可變序列

tuple函數

>>> tuple('zhou')
('z', 'h', 'o', 'u')
>>> 


第三章:使用字符串

format="hello, %s, %s, enough for yo?"
values=('world','Hot')
print format % values
#hello, world, Hot, enough for yo?
字符串方法

1)find

>>> 'zhouwei,nihao'.find('ni')
8
>>> 
2)join(反過程:split)

>>> seq=['1','2','3','4']
>>> sep='+'
>>> sep.join(seq)
'1+2+3+4'
>>> 
3)lower

>>> 'ZhouWei'.lower()
'zhouwei'
>>> 

4) replace

>>> 'This is the test'.replace('is','eez')
'Theez eez the test'
>>> 


第四章:字典:當索引不好用時

字典(mapping,dict)是Python中唯一內建的映射類型。字典中沒有特殊的順序,key可以使數字,字符串或元祖。

>>> items=[('name','zhouwei'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'zhouwei'}
>>> d['name']
'zhouwei'
>>> x={}
>>> x['name']='zhouwei'
>>> x['name']
'zhouwei'
>>> 
字典的格式化字符串

phonebook={'Beth':'9123','Alice':'2234','cecil':'324'}
print "Ceil's phone number is %(cecil)s."%phonebook
# Ceil's phone number is 324.



Pyton 多線程實現機制

python是支持多線程的,並且是native的線程。主要是通過thread和threading這兩個模塊來實現的. 本文提供多線程實現的兩種方式及讓多條命令併發執行的代碼樣例

# Filename: thread-extends-class.py
# 直接從Thread繼承,創建一個新的class,把線程執行的代碼放到這個新的 class裏
import threading
import time
  
class ThreadImpl(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self._num = num
  
    def run(self):
        global total, mutex
         
        # 打印線程名
        print threading.currentThread().getName()
  
        for x in xrange(0, int(self._num)):
            # 取得鎖
            mutex.acquire()
            total = total + 1
            # 釋放鎖
            mutex.release()
  
if __name__ == '__main__':
    #定義全局變量
    global total, mutex
    total = 0
    # 創建鎖
    mutex = threading.Lock()
     
    #定義線程池
    threads = []
    # 創建線程對象
    for x in xrange(0, 40):
        threads.append(ThreadImpl(100))
    # 啓動線程
    for t in threads:
        t.start()
    # 等待子線程結束
    for t in threads:
        t.join()  
     
    # 打印執行結果
    print total


# encoding=utf-8
# Filename: thread-function.py
# 創建線程要執行的函數,把這個函數傳遞進Thread對象裏,讓它來執行
 
import threading
import time
  
def threadFunc(num):
    global total, mutex
     
    # 打印線程名
    print threading.currentThread().getName()
  
    for x in xrange(0, int(num)):
        # 取得鎖
        mutex.acquire()
        total = total + 1
        # 釋放鎖
        mutex.release()
  
def main(num):
    #定義全局變量
    global total, mutex
    total = 0
    # 創建鎖
    mutex = threading.Lock()
     
    #定義線程池
    threads = []
    # 先創建線程對象
    for x in xrange(0, num):
        threads.append(threading.Thread(target=threadFunc, args=(100,)))
    # 啓動所有線程
    for t in threads:
        t.start()
    # 主線程中等待所有子線程退出
    for t in threads:
        t.join()  
         
    # 打印執行結果
    print total
  
  
if __name__ == '__main__':
    # 創建40個線程
    main(40)

# encoding=utf-8
# Filename: put_files_hdfs.py
# 讓多條命令併發執行,如讓多條scp,ftp,hdfs上傳命令併發執行,提高程序運行效率
import datetime
import os
import threading
 
def execCmd(cmd):
    try:
        print "命令%s開始運行%s" % (cmd,datetime.datetime.now())
        os.system(cmd)
        print "命令%s結束運行%s" % (cmd,datetime.datetime.now())
    except Exception, e:
        print '%s\t 運行失敗,失敗原因\r\n%s' % (cmd,e)
 
if __name__ == '__main__':
    # 需要執行的命令列表
    cmds = ['ls /root',
           'pwd',]
     
    #線程池
    threads = []
     
    print "程序開始運行%s" % datetime.datetime.now()
 
    for cmd in cmds:
        th = threading.Thread(target=execCmd, args=(cmd,))
        th.start()
        threads.append(th)
          
    # 等待線程運行完畢
    for th in threads:
        th.join()
          
    print "程序結束運行%s" % datetime.datetime.now()









PEP8:Python編程規範;

http://legacy.python.org/dev/peps/pep-0008/




Python 開源框架,

Python 服務器原型開發

http://ciniao.me/article.php?id=9

http://ciniao.me/article.php?id=10

http://blog.csdn.net/taozc/article/details/7532785


先把Python網絡編程給大體看了,練習幾個例子,具體網絡編程見:《Foundations of Python network programming.djvu

有關Python Twisted網絡編程框架的書《Twisted Network Programming Essentials》官網:https://twistedmatrix.com/trac/


sock模塊

https://docs.python.org/2/library/socket.html

urllib和urllib2模塊

https://docs.python.org/2/library/urllib.html

https://docs.python.org/2/library/urllib2.html

SocketServer模塊

https://docs.python.org/2/library/socketserver.html#module-SocketServer


Asyncore和Asynchat模塊的介紹(標準庫中事件驅動型框架,select和poll)

https://docs.python.org/2/library/asyncore.html

https://docs.python.org/2/library/asynchat.html#module-asynchat


HTMLParser

https://docs.python.org/2/library/htmlparser.html


cgi

http://www.w3cschool.cc/python/python-cgi.html

https://docs.python.org/2/library/cgi.html

https://docs.python.org/2/library/cgitb.html


發佈了45 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章