天天看點

python程式必知面試題 Python面試題彙總

Python面試題彙總

拿網絡上關于Python的面試題彙總了,給出了自認為合理的答案,有些題目不錯,可以從中學到點什麼,答案如不妥,請指正......

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

【題目:001】| 說說你對zen of python的了解,你有什麼辦法看到它?

Python之禅,Python秉承一種獨特的簡潔和可讀行高的文法,以及高度一緻的程式設計模式,符合“大腦思維習慣”,使Python易于學習、了解和記憶。Python同時采用了一條極簡主義的設計理念,了解完整的Python哲學理念,可以在任何一個Python互動解釋器中鍵入import this指令,這是Python隐藏的一個彩蛋:描繪了一系列Python設計原則。如今已是Python社群内流行的行話"EIBTI",明了勝于晦澀這條規則的簡稱. 在Python的思維方式中,明了勝于晦澀,簡潔勝于複雜。

[python]  view plain  copy

  1. >>> import this    
  2. The Zen of Python, by Tim Peters    
  3. Beautiful is better than ugly.    
  4. Explicit is better than implicit.    
  5. Simple is better than complex.    
  6. Complex is better than complicated.    
  7. Flat is better than nested.    
  8. Sparse is better than dense.    
  9. Readability counts.    
  10. Special cases aren't special enough to break the rules.    
  11. Although practicality beats purity.    
  12. Errors should never pass silently.    
  13. Unless explicitly silenced.    
  14. In the face of ambiguity, refuse the temptation to guess.    
  15. There should be one-- and preferably only one --obvious way to do it.    
  16. Although that way may not be obvious at first unless you're Dutch.    
  17. Now is better than never.    
  18. Although never is often better than *right* now.    
  19. If the implementation is hard to explain, it's a bad idea.    
  20. If the implementation is easy to explain, it may be a good idea.    
  21. Namespaces are one honking great idea -- let's do more of those!    

【題目:002】| 說說你對pythonic的看法,嘗試解決下面的小問題

#簡潔,明了,嚴謹,靈活

[python]  view plain  copy

  1. #交換兩個變量值    
  2. a,b = b,a    
  3. #去掉list中的重複元素    
  4. old_list = [1,1,1,3,4]    
  5. new_list = list(set(old_list))    
  6. #翻轉一個字元串    
  7. s = 'abcde'    
  8. ss = s[::-1]    
  9. #用兩個元素之間有對應關系的list構造一個dict    
  10. names = ['jianpx', 'yue']    
  11. ages = [23, 40]    
  12. m = dict(zip(names,ages))    
  13. #将數量較多的字元串相連,如何效率較高,為什麼    
  14. fruits = ['apple', 'banana']    
  15. result = ''.join(fruits)    
  16. #python字元串效率問題之一就是在連接配接字元串的時候使用‘+’号,例如 s = ‘s1’ + ‘s2’ + ‘s3’ + ...+’sN’,總共将N個字元串連接配接起來, 但是使用+号的話,python需要申請N-1次記憶體空間, 然後進行字元串拷貝。原因是字元串對象PyStringObject在python當中是不可變 對象,是以每當需要合并兩個字元串的時候,就要重新申請一個新的記憶體空間 (大小為兩個字元串長度之和)來給這個合并之後的新字元串,然後進行拷貝。 是以用+号效率非常低。建議在連接配接字元串的時候使用字元串本身的方法 join(list),這個方法能提高效率,原因是它隻是申請了一次記憶體空間, 因為它可以周遊list中的元素計算出總共需要申請的記憶體空間的大小,一次申請完。    

【題目:003 】|   你調試python代碼的方法有哪些?

[python]  view plain  copy

  1. 具體IDE都有調試,比如:IDLE, Eclipse+Pydev都可以設定斷點調試。   
  2. pdb子產品也可以做調試。  
  3. 還有PyChecker和Pylint  
  4. PyChecker是一個python代碼的靜态分析工具,它可以幫助查找python代碼的bug, 會對代碼的複雜度和格式提出警告    
  5. Pylint   是另外一個工具可以進行coding standard檢查。   

【題目:004 】|   你在github上都fork過哪些python庫,列舉一下你經常使用的,每個庫用一句話描述下其功能

[python]  view plain  copy

  1. http://rogerdudler.github.io/git-guide/index.zh.html    #關于git簡明指南    
  2. http://www.zhihu.com/question/20070065                  #關于git的BBS    
  3. http://www.techug.com/githug-for-designer               #關于github的    

【題目:005 】|     什麼是GIL?

[python]  view plain  copy

  1. 什麼是GIL(Global Interpreter Lock)全局解釋器鎖? 簡單地說就是:  
  2. 每一個interpreter程序,隻能同時僅有一個線程來執行, 獲得相關的鎖, 存取相關的資源.  
  3. 那麼很容易就會發現,如果一個interpreter程序隻能有一個線程來執行,   
  4. 多線程的并發則成為不可能, 即使這幾個線程之間不存在資源的競争.  
  5. 從理論上講,我們要盡可能地使程式更加并行, 能夠充分利用多核的功能.  

【 題目:006】 |  什麼是元類(meta_class)?

[python]  view plain  copy

  1. 元類就是用來建立類的“東西”  
  2. 詳情操作: http://blog.jobbole.com/21351/  

【 題目:007 】|  對比一下dict中items與iteritems?

[python]  view plain  copy

  1. >>> D = {'a':1,'b':2,'c':3,'d':4}    
  2. >>> D.items()                       #一次性取出所有    
  3. [('a', 1), ('c', 3), ('b', 2), ('d', 4)]    
  4. >>> D.iteritems()                   #疊代對象,每次取出一個。用for循環周遊出來;    
  5. <dictionary-itemiterator object at 0x00000000026243B8>    
  6. >>> for i in D.iteritems():    
  7. ...   print i,    
  8. ...    
  9. ('a', 1) ('c', 3) ('b', 2) ('d', 4)    
  10. >>> for k,v in D.iteritems():    
  11. ...   print k,    
  12. ...    
  13. a c b d    
  14. 總結:   
  15. 1. 一般iteritems()疊代的辦法比items()要快,特别是資料庫比較大時。  
  16. 2. 在Python3中一般取消前者函數  

【 題目:008 】|  是否遇到過python的子產品間循環引用的問題,如何避免它?

[python]  view plain  copy

  1. 這是代碼結構設計的問題,子產品依賴和類依賴  
  2. 如果老是覺得碰到循環引用,很可能是子產品的分界線劃錯地方了。可能是把應該在一起的東西硬拆開了,可能是某些職責放錯地方了,可能是應該抽象的東西沒抽象  
  3. 總之微觀代碼規範可能并不能幫到太多,重要的是更宏觀的劃分子產品的經驗技巧,推薦uml,腦圖,白闆等等圖形化的工具先梳理清楚整個系統的總體結構和職責分工  
  4. 采取辦法,從設計模式上來規避這個問題,比如:  
  5. 1. 使用 “__all__” 白名單開放接口  
  6. 2. 盡量避免 import  

【 題目:009 】|  有用過with statement嗎?它的好處是什麼?

[python]  view plain  copy

  1. >>> with open('text.txt') as myfile:    
  2. ...   while True:    
  3. ...     line = myfile.readline()    
  4. ...     if not line:    
  5. ...       break    
  6. ...     print line,    
  7. # with語句使用所謂的上下文管理器對代碼塊進行包裝,允許上下文管理器實作一些設定和清理操作。    
  8. # 例如:檔案可以作為上下文管理器使用,它們可以關閉自身作為清理的一部分。    
  9. # NOTE:在PYTHON2.5中,需要使用from __future__ import with_statement進行with語句的導入    

【題目:010】 | 用Python生成指定長度的斐波那契數列

[python]  view plain  copy

  1. def fibs(x):  
  2.     result = [0, 1]  
  3.     for index in range(x-2):  
  4.         result.append(result[-2]+result[-1])  
  5.     return result  
  6. if __name__=='__main__':  
  7.     num = input('Enter one number: ')  
  8.     print fibs(num)  

【題目:011】 |   Python裡如何生産随機數

[python]  view plain  copy

  1. >>> import random  
  2. >>> random.random()  
  3. 0.29495314937268713  
  4. >>> random.randint(1,11)  
  5. 8  
  6. >>> random.choice(range(11))  
  7. 3  

【題目:012】 |   Python裡如何反序的疊代一個序列

[python]  view plain  copy

  1. 如果是一個list, 最快的解決方案是:  
  2. list.reverse()  
  3. try:  
  4.     for x in list:  
  5.         “do something with x”  
  6. finally:  
  7.     list.reverse()  
  8. 如果不是list, 最通用但是稍慢的解決方案是:  
  9. for i in range(len(sequence)-1, -1, -1):  
  10. x = sequence[i]  

【題目:013】 |   Python中如何定義一個函數

[python]  view plain  copy

  1. def func(arg, *args, **kwagrs):   #普通函數  
  2.     func_body  
  3.     return   
  4. lambda x: x **2                   #匿名函數  

【題目:014】 |   Python比對HTML tag的時候,<.*>和<.*?>有什麼差別

[python]  view plain  copy

  1. import re  
  2. s = ‘<html><head><title>Title</title>’  
  3. print(re.match(‘<.*>’, s).group())  
  4. 會傳回一個比對<html><head><title>Title</title>而不是<html>  
  5. 而  
  6. import re  
  7. s = ‘<html><head><title>Title</title>’  
  8. print(re.match(‘<.*?>’, s).group())  
  9. 則會傳回<html>  
  10. <.*>這種比對稱作貪心比對 <.*?>稱作非貪心比對  

【題目:015】 |   Python裡面search()和match()的差別 [python]  view plain  copy

  1. >>> import re  
  2. >>> re.match(r'python','Programing Python, should be pythonic')  
  3. >>> obj1 = re.match(r'python','Programing Python, should be pythonic')  #傳回None  
  4. >>> obj2 = re.search(r'python','Programing Python, should be pythonic') #找到pythonic  
  5. >>> obj2.group()  
  6. 'python'  
  7. #re.match隻比對字元串的開始,如果字元串開始不符合正規表達式,則比對失敗,函數傳回None;  
  8. #re.search比對整個字元串,直到找到一個比對。  

【題目:016】 |   Python程式中文輸出問題怎麼解決

[python]  view plain  copy

  1. 在Python3中,對中文進行了全面的支援,但在Python2.x中需要進行相關的設定才能使用中文。否則會出現亂碼。  
  2. Python預設采取的ASCII編碼,字母、标點和其他字元隻使用一個位元組來表示,但對于中文字元來說,一個位元組滿足不了需求。  
  3. 為了能在計算機中表示所有的中文字元,中文編碼采用兩個位元組表示。如果中文編碼和ASCII混合使用的話,就會導緻解碼錯誤,進而才生亂碼。  
  4. 解決辦法:  
  5. 互動式指令中:一般不會出現亂碼,無需做處理   
  6. py腳本檔案中:跨字元集必須做設定,否則亂碼  
  7. 1. 首先在開頭一句添加:  
  8. # coding = utf-8    
  9. # 或    
  10. # coding = UTF-8    
  11. # 或    
  12. # -*- coding: utf-8 -*-   
  13. 2. 其次需将檔案儲存為UTF-8的格式!  
  14. 3. 最後: s.decode('utf-8').encode('gbk')  

【題目:017】 |   什麼是lambda函數

[python]  view plain  copy

  1. 函數使用:  
  2. 1. 代碼塊重複,這時候必須考慮到函數,降低程式的備援度  
  3. 2. 代碼塊複雜,這時候必須考慮到函數,降低程式的複雜度  
  4. Python有兩種函數,一種是def定義,一種是lambda函數()  
  5. 當程式代碼很短,且該函數隻使用一次,為了程式的簡潔,及節省變量記憶體占用空間,引入了匿名函數這個概念  
  6. >>> nums = range(2,20)  
  7. >>> for i in nums:  
  8.         nums = filter(lambda x:x==i or x % i,nums)  
  9. >>> nums  
  10. [2, 3, 5, 7, 11, 13, 17, 19]  

【題目:018】 |   Python裡面如何實作tuple和list的轉換

[python]  view plain  copy

  1. #From list to Tuple                   
  2. tuple(a_list)     
  3. #From Tuple to List  
  4. def to_list(t):   
  5.     return [i if not isinstance(i,tuple) else to_list(i) for i in t]  

【題目:019】 |   請寫出一段Python代碼實作删除一個list裡面的重複元素

[python]  view plain  copy

  1. >>> L1 = [4,1,3,2,3,5,1]  
  2. >>> L2 = []  
  3. >>> [L2.append(i) for i in L1 if i not in L2]  
  4. >>> print L2  
  5. [4, 1, 3, 2, 5]  

【題目:020】 |   Python是如何進行類型轉換的

[python]  view plain  copy

  1. >>> int('1234')                   # 将數字型字元串轉為整形  
  2. 1234  
  3. >>> float(12)                     # 将整形或數字字元轉為浮點型  
  4. 12.0  
  5. >>> str(98)                       # 将其他類型轉為字元串型  
  6. '98'  
  7. >>> list('abcd')                  # 将其他類型轉為清單類型  
  8. ['a', 'b', 'c', 'd']  
  9. >>> dict.fromkeys(['name','age']) # 将其他類型轉為字典類型  
  10. {'age': None, 'name': None}  
  11. >>> tuple([1, 2, 3, 4])           # 将其他類型轉為元祖類型  
  12. (1, 2, 3, 4)  

詳細轉換總結如下:

[python]  view plain  copy

  1. 函數                      描述  
  2. int(x [,base])              将x轉換為一個整數  
  3. long(x [,base] )            将x轉換為一個長整數  
  4. float(x)                    将x轉換到一個浮點數  
  5. complex(real [,imag])       建立一個複數  
  6. str(x)                      将對象 x 轉換為字元串  
  7. repr(x)                     将對象 x 轉換為表達式字元串  
  8. eval(str)                   用來計算在字元串中的有效Python表達式,并傳回一個對象  
  9. tuple(s)                    将序列 s 轉換為一個元組  
  10. list(s)                     将序列 s 轉換為一個清單  
  11. set(s)                      轉換為可變集合  
  12. dict(d)                     建立一個字典。d 必須是一個序列 (key,value)元組。  
  13. frozenset(s)                轉換為不可變集合  
  14. chr(x)                      将一個整數轉換為一個字元  
  15. unichr(x)                   将一個整數轉換為Unicode字元  
  16. ord(x)                      将一個字元轉換為它的整數值  
  17. hex(x)                      将一個整數轉換為一個十六進制字元串  
  18. oct(x)                      将一個整數轉換為一個八進制字元串  

【題目:021】|  如何知道一個Python對象的類型

[python]  view plain  copy

  1. >>> type([]);type('');type(0);type({});type(0.0);type((1,))  
  2. <type 'list'>  
  3. <type 'str'>  
  4. <type 'int'>  
  5. <type 'dict'>  
  6. <type 'float'>  
  7. <type 'tuple'>  

【題目:022】|  Python裡面如何拷貝一個對象

[python]  view plain  copy

  1. 切片S[:]  # 注不能應用于字典  
  2. 深淺寶貝  # 能應用于所有序列和字典  
  3. 1. 淺拷貝D.copy()方法  
  4. 2. 深拷貝deepcopy(D)方法  

【題目:023】 |   Python中pass語句的作用是什麼 [python]  view plain  copy

  1. pass語句什麼也不做,一般作為占位符或者建立占位程式  

【題目:024】 |   寫一段程式逐行讀入一個文本檔案,并在螢幕上列印出來 [python]  view plain  copy

  1. f = open(filename)    
  2. while True:    
  3.     line = f.readline()    
  4.     if not line: break    
  5.     print(line)    
  6. f.close()    

【題目:025】 |   如何用Python删除一個檔案 [python]  view plain  copy

  1. import os  
  2. os.remove(filename)  

【題目:026】 |   Python代碼得到清單list的交集與差集 [python]  view plain  copy

  1. >>> list1 = [1, 3, 4, 6]  
  2. >>> list2 = [1, 2, 3, 4]  
  3. >>> [i for i in list1 if i not in list2]  
  4. [6]  
  5. >>> [i for i in list1 if i in list2]  
  6. [1, 3, 4]  

【題目:027】 |   Python是如何進行記憶體管理的

[python]  view plain  copy

  1. python内部使用引用計數,來保持追蹤記憶體中的對象,Python内部記錄了對象有多少個引用,即引用計數,當對象被建立時就建立了一個引用計數,當對象不再需要時,這個對象的引用計數為0時,它被垃圾回收。所有這些都是自動完成,不需要像C一樣,人工幹預,進而提高了程式員的效率和程式的健壯性。  

【題目:028】 |   介紹一下Python下range()函數的用法

[python]  view plain  copy

  1. >>> range(10)  
  2. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
  3. >>> range(1, 10)  
  4. [1, 2, 3, 4, 5, 6, 7, 8, 9]  
  5. >>> range(0, 9, 2)  
  6. [0, 2, 4, 6, 8]  
  7. >>> range(99,0,-10)  
  8. [99, 89, 79, 69, 59, 49, 39, 29, 19, 9]  
  9. 相差別的是xrange(),每次隻取出一個疊代對象,如果是資料量比較大時,效率較高  
  10. 在Python3中,沒有xrange()函數,其功能放在了range()函數上  

【題目:029】|  Python異常處理介紹一下

[python]  view plain  copy

  1. 程式中出現異常情況時就需要異常處理。比如當你打開一個不存在的檔案時。當你的程式中有  
  2. 一些無效的語句時,Python會提示你有錯誤存在。下面是一個拼寫錯誤的例子,print寫成了Print  
  3. 下面是異常最常見的幾種角色  
  4. 1. 錯誤處理  
  5. >>>可以在程式代碼中捕捉和相應錯誤,或者忽略已發生的異常。  
  6. >>>如果忽略錯誤,PYTHON預設的異常處理行為将啟動:停止程式,列印錯誤資訊。  
  7. >>>如果不想啟動這種預設行為,就用try語句來捕捉異常并從異常中恢複。  
  8. 2. 事件通知  
  9. >>>異常也可用于發出有效狀态的信号,而不需在程式間傳遞結果标志位。或者刻意對其進行測試  
  10. 3. 特殊情況處理  
  11. >>>有時,發生了某種很罕見的情況,很難調整代碼區處理。通常會在異常進行中處理,進而省去應對特殊情況的代碼  
  12. 4. 終止行為  
  13. >>>try/finally語句可確定一定會進行需要的結束運算,無論程式是否有異常  
  14. 5. 非正常控制流程  

【題目:030】 |   介紹一下Python中的filter方法 [python]  view plain  copy

  1. filter就像map,reduce,apply,zip等都是内置函數,用C語言實作,具有速度快,功能強大等  
  2. 優點。  
  3. 用于過濾與函數func()不比對的值, 類似于SQL中select value != 'a'  
  4. 相當于一個疊代器,調用一個布爾函數func來疊代seq中的每個元素,傳回一個是bool_seq返  
  5. 回為True的序列  
  6. >>>第一個參數: function or None, 函數或None  
  7. >>>第二個參數: sequence,序列  

【題目:031】 |   介紹一下except的用法和作用 [python]  view plain  copy

  1. try/except:          捕捉由PYTHON自身或寫程式過程中引發的異常并恢複  
  2. except:              捕捉所有其他異常  
  3. except name:         隻捕捉特定的異常  
  4. except name, value:  捕捉異常及格外的資料(執行個體)  
  5. except (name1,name2) 捕捉列出來的異常  
  6. except (name1,name2),value: 捕捉任何列出的異常,并取得額外資料  
  7. else:                如果沒有引發異常就運作  
  8. finally:             總是會運作此處代碼  

【題目:032】 |   如何用Python來進行查詢和替換一個文本字元串

[python]  view plain  copy

  1. >>> words = 'Python is a very funny language!'  
  2. >>> words.find('Python')             # 傳回的為0或正數時,為其索引号  
  3. >>> words.find('is')  
  4. 7  
  5. >>> words.find('dafa')               # 傳回-1表示查找失敗  
  6. -1  
  7. >>> words.replace('Python', 'Perl')  # replace()替換  
  8. 'Perl is a very funny language!'  

【題目:033】 |   Python如何copy一個檔案

[python]  view plain  copy

  1. import shutil  
  2. shutil.copyfile('a.py', 'copy_a.py')  

【題目:034】|  Python判斷目前使用者是否是root

[python]  view plain  copy

  1. import os  
  2. if os.getuid() != 0:    # root賬号的uid=0  
  3.     print os.getuid()  
  4.     print 'Should run as root account'  
  5. else:  
  6.     print 'Hello, Root!'  

【題目:035】 |   用Python寫一個for循環的例子

[python]  view plain  copy

  1. for循環可以周遊序列(清單,字元串,元祖),range()及疊代對象,如xrange()  
  2. names = ['Alice', 'Betty', 'Fred', 'Tom']  
  3. for index, name in enumerate(names):  
  4.     print 'index:',index,'=>', name  
  5. # 輸出結果    
  6. index: 0 => Alice  
  7. index: 1 => Betty  
  8. index: 2 => Fred  
  9. index: 3 => Tom  

【題目:036】 |   介紹一下Python中webbrowser的用法

[python]  view plain  copy

  1. webbrowser子產品提供了一個進階接口來顯示基于Web的文檔,大部分情況下隻需要簡單的調用open()方法。  
  2. webbrowser定義了如下的異常:exception webbrowser.Error, 當浏覽器控件發生錯誤是會抛出這個異常  
  3. webbrowser有以下方法:  
  4. webbrowser.open(url[, new=0[, autoraise=1]])  
  5. 這個方法是在預設的浏覽器中顯示url, 如果new = 0, 那麼url會在同一個浏覽器視窗下打開,如果new = 1, 會打開一個新的視窗,如果new = 2, 會打開一個新的tab, 如果autoraise = true, 視窗會自動增長。  
  6. webbrowser.open_new(url)  
  7. 在預設浏覽器中打開一個新的視窗來顯示url, 否則,在僅有的浏覽器視窗中打開url  
  8. webbrowser.open_new_tab(url)  
  9. 在預設浏覽器中當開一個新的tab來顯示url, 否則跟open_new()一樣  
  10. webbrowser.get([name]) 根據name傳回一個浏覽器對象,如果name為空,則傳回預設的浏覽器  
  11. webbrowser.register(name, construtor[, instance])  
  12. 注冊一個名字為name的浏覽器,如果這個浏覽器類型被注冊就可以用get()方法來擷取。  

【題目:037】 |   默寫盡可能多的str對象的方法

[python]  view plain  copy

  1. #方法                                   #描述    
  2. -------------------------------------------------------------------------------------------------    
  3. S.capitalize()                          #傳回首字母大寫的字元串的副本    
  4. S.center(width[,fillchar])              #傳回一個長度為max(len(S),width),S居中,兩側fillchar填充    
  5. S.count(sub[,start[,end]])              #計算子字元串sub的出現次數,可将搜尋範圍限制為S[start:end]    
  6. S.decode([encoding[,error]])            #傳回使用給定編碼方式的字元串的解碼版本,由error指定錯誤處理方式    
  7. S.endswith(suffix[start[,end]])         #檢查S是否以suffix結尾,可給定[start:end]來選擇比對的範圍    
  8. S.expandtabs([tabsize])                 #傳回字元串的副本,其中tab字元會使用空格進行擴充,可選擇tabsize    
  9. S.find(sun[,start[,end]])               #傳回子字元串sub的第一個索引,不存在則為-1,可選擇搜尋範圍    
  10. S.index(sub[,start[,end]])              #傳回子字元串sub的第一個索引,不存在則引發ValueError異常.    
  11. S.isalnum()                             #檢查字元串是否由字母或數字字元組成    
  12. S.isalpha()                             #檢查字元串是否由字母字元組成    
  13. S.isdigit()                             #檢查字元串是否由數字字元組成    
  14. S.islower()                             #檢查字元串是否由小寫字母組成    
  15. S.isspace()                             #檢查字元串是否由空格組成    
  16. S.istitle()                             #檢查字元串時候首字母大寫    
  17. S.isupper()                             #檢查字元串是否由大寫字母組成    
  18. S.join(sequence)                        #傳回其中sequence的字元串元素由S連接配接的字元串    
  19. S.ljust(width[,fillchar])               #傳回S副本左對齊的字元串,長度max(len(S),W),右側fillchar填充    
  20. S.lower()                               #傳回所有字元串都為小寫的副本    
  21. S.lstrip([char])                        #向左移除所有char,預設移除(空格,tab,\n)    
  22. S.partition(seq)                        #在字元串中搜尋seq并傳回    
  23. S.replace(old,new[,max])                #将new替換olad,最多可替換max次    
  24. S.rfind(sub[,start[,end]])              #傳回sub所在的最後一個索引,不存在則為-1,可定搜尋範圍S[start:end]    
  25. S.rindex(sub[,start[,end]])             #傳回sub所在的最後一個索引,不存在則會引發ValueError異常。    
  26. S.rjust(width[,fillchar])               #傳回S副本右對齊的字元串,長度max(len(S),W),左側fillchar填充    
  27. S.rpartition(seq)                       #同Partition,但從右側開始查找    
  28. S.rstip([char])                         #向右移除所有char,預設移除(空格,tab,\n)    
  29. S.rsplit(sep[,maxsplit])                #同split,但是使用maxsplit時是從右往左進行計數    
  30. S.split(sep[,maxsplit])                 #使用sep做為分割符,可使用maxsplit指定最大切分數    
  31. S.zfill(width)                          #在S的左側以0填充width個字元    
  32. S.upper()                               #傳回S的副本,所有字元大寫    
  33. S.splitlines([keepends])                #傳回S中所有行的清單,可選擇是否包括換行符    
  34. S.startswith(prefix[,start[,end]])      #檢查S是否以prefix開始,可用[start,end]來定義範圍    
  35. S.strip([chars])                        #移除所有字元串中含chars的字元,預設移除(空格,tab,\n)    
  36. S.swapcase()                            #傳回S的副本,所有大小寫交換    
  37. S.title()                               #傳回S的副本,所有單詞以大寫字母開頭    
  38. S.translate(table[,deletechars])        #傳回S的副本,所有字元都使用table進行的轉換,可選擇删除出現在deletechars中的所有字元    

【題目:038】 |   現在有一個dict對象adict,裡面包含了一百萬個元素,查找其中的某個元素的平均需要多少次比較 [python]  view plain  copy

  1. O(1)  哈希字典,快速查找,鍵值映射,鍵唯一!  

【題目:039】 |   有一個list對象alist,裡面的所有元素都是字元串,編寫一個函數對它實作一個大小寫無關的排序 [python]  view plain  copy

  1. words = ['This','is','a','dog','!']  
  2. words.sort(key=lambda x:x.lower())  
  3. print words  
  4. #輸出結果  
  5. >>>   
  6. ['!', 'a', 'dog', 'is', 'This']  

【題目:040】 |  有一個排好序地list對象alist,查找其中是否有某元素a [python]  view plain  copy

  1. alist = ['a','s','d','f']  
  2. try:  
  3.     alist.index('a')  
  4.     print 'Find it.'  
  5. except ValueError:  
  6.     print 'Not Found.'  

【題目:041】 |  請用Python寫一個擷取使用者輸入數字,并根據數字大小輸出不同資訊的腳本 [python]  view plain  copy

  1. num = input('Enter number: ')  
  2. if num > 100:  
  3.     print 'The number is over 100'  
  4. elif 0 < num <= 100:  
  5.     print 'The number is between 0~100'  
  6. elif num < 0:  
  7.     print 'The number is negative.'  
  8. else:  
  9.     print 'Not a number'  

【題目:042】 |  打亂一個排好序的list對象alist [python]  view plain  copy

  1. # random子產品中的shuffle(洗牌函數)  
  2. import random  
  3. alist = [1, 2, 3, 4]  
  4. random.shuffle(alist)     
  5. print alist  

【題目:043】 |  有二維的list對象alist,假定其中的所有元素都具有相同的長度,寫一段程式根據元素的第二個元素排序 [python]  view plain  copy

  1. def sort_lists(lists, sord, idx):  
  2.     if sord == 'desc':  
  3.         lists.sort(key=lambda x:x[idx], reverse=True)  
  4.     else:  
  5.         lists.sort(key=lambda x:x[idx])  
  6.     return lists  
  7. lists = [['cd','ab'],['ef','ac']]  
  8. sort_lists(lists,'desc',1)  
  9. print lists  
  10. # 輸出結果  
  11. >>>   
  12. [['ef', 'ac'], ['cd', 'ab']]  

【題目:044】 |  inspect子產品有什麼用 [python]  view plain  copy

  1. inspect子產品提供了一系列函數用于幫助使用自省。  
  2. 檢查對象類型  
  3. is{module|class|function|method|builtin}(obj): 檢查對象是否為子產品、類、函數、方法、内建函數或方法。  
  4. isroutine(obj): 用于檢查對象是否為函數、方法、内建函數或方法等等可調用類型。  
  5. 擷取對象資訊  
  6. getmembers(object[, predicate]): 這個方法是dir()的擴充版,它會将dir()找到的名字對應的屬性一并傳回。  
  7. getmodule(object): 它傳回object的定義所在的子產品對象。  
  8. get{file|sourcefile}(object): 擷取object的定義所在的子產品的檔案名|源代碼檔案名(如果沒有則傳回None)。  
  9. get{source|sourcelines}(object): 擷取object的定義的源代碼,以字元串|字元串清單傳回。  
  10. getargspec(func): 僅用于方法,擷取方法聲明的參數,傳回元組,分别是(普通參數名的清單, *參數名, **參數名, 預設值元組)。   

【題目:045】 |  Python處理指令行參數示例代碼 [python]  view plain  copy

  1. # 最簡單、最原始的方法就是手動解析了  
  2. import sys  
  3. for arg in sys.argv[1:]:  
  4.     print(arg)  

【題目:046】|  介紹一下Python getopt子產品

[python]  view plain  copy

  1. # getopt子產品是原來的指令行選項解析器,支援UNIX函數getopt()建立的約定。  
  2. # 它會解析一個參數序列,如sys.argv,并傳回一個元祖序列和一個非選項參數序列。  
  3. # 目前支援的選項文法包括短格式和長格式選項:-a, -bval, -b val, --noarg, --witharg=val, --witharg val。  
  4. # 如果隻是簡單的指令行解析,getopt還是不錯的選擇。一個例子如下  
  5. import sys  
  6. import getopt  
  7. try:  
  8.     options, remainder = getopt.getopt(sys.argv[1:], 'o:v', ['output=', 'verbose', 'version=',])  
  9. except getopt.GetoptError as err:  
  10.     print 'ERROR:', err  
  11.     sys.exit(1)  
  12. 總結下getopt的特點:1.  getopt是從前到後解析 2.  getopt不檢查額外參數的合法性,需要自行檢查           3.  短指令行和長指令行是分開解析的</span>  

【題目:047】 |   Python清單與元組的差別是什麼?分别在什麼情況下使用?

[python]  view plain  copy

  1. Python中清單和元祖都是序列,是以都能進行添加,删除,更新,切片等操作。但清單是可變對象,元祖是不可變對象。  
  2. 元祖主要用于函數指派,字元串格式化等。但清單中的方法更多些,也是PYTHON中更常用的資料結構。  

【題目:048】|  有一個長度是101的數組,存在1~100的數字,有一個是重複的,拿重複的找出來

[python]  view plain  copy

  1. # Python中,主要是拿count(i) ==2的找出來即可,再利用清單推導式  
  2. >>> l = [1, 2, 3, 4, 2]  
  3. >>> tmp = []  
  4. >>> [tmp.append(i) for i in l if l.count(i) == 2]  
  5. [None, None]  
  6. >>> tmp  
  7. [2, 2]  
  8. >>> set(tmp)  
  9. set([2])  

【題目:049】|  set是在哪個版本成為build-in types的?舉例說明,并說明為什麼當時選擇了set這種資料結構

[python]  view plain  copy

  1. python的set和其他語言類似, 是一個無序不重複元素集, 基本功能包括關系測試和消除重複元素. 集合對象還支援union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算.  
  2. sets 支援 x in set, len(set),和 for x in set。作為一個無序的集合,sets不記錄元素位置或者插入點。是以,sets不支援 indexing, slicing, 或其它類序列(sequence-like)的操作。  
  3. 下面來點簡單的小例子說明。  
  4. >>> x = set('spam')  
  5. >>> y = set(['h','a','m'])  
  6. >>> x, y  
  7. (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))  
  8. 再來些小應用。  
  9. >>> x & y # 交集  
  10. set(['a', 'm'])  
  11. >>> x | y # 并集  
  12. set(['a', 'p', 's', 'h', 'm'])  
  13. >>> x - y # 差集  
  14. set(['p', 's'])  
  15. 去除海量清單裡重複元素,用hash來解決也行,隻不過感覺在性能上不是很高,用set解決還是很不錯的,示例如下:  
  16. >>> a = [11,22,33,44,11,22]  
  17. >>> b = set(a)  
  18. >>> b  
  19. set([33, 11, 44, 22])  
  20. >>> c = [i for i in b]  
  21. >>> c  
  22. [33, 11, 44, 22]  
  23. 很酷把,幾行就可以搞定。  
  24. 1.8 集合   
  25. 集合用于包含一組無序的對象。要建立集合,可使用set()函數并像下面這樣提供一系列的項:  
  26. s = set([3,5,9,10])      #建立一個數值集合  
  27. t = set("Hello")         #建立一個唯一字元的集合  
  28. 與清單和元組不同,集合是無序的,也無法通過數字進行索引。此外,集合中的元素不能重複。例如,如果檢查前面代碼中t集合的值,結果會是:  
  29. >>> t  
  30. set(['H', 'e', 'l', 'o'])  
  31. 注意隻出現了一個'l'。  
  32. 集合支援一系列标準操作,包括并集、交集、差集和對稱差集,例如:  
  33. a = t | s          # t 和 s的并集  
  34. b = t & s          # t 和 s的交集  
  35. c = t – s         # 求差集(項在t中,但不在s中)  
  36. d = t ^ s          # 對稱差集(項在t或s中,但不會同時出現在二者中)  
  37. 基本操作:  
  38. t.add('x')            # 添加一項  
  39. s.update([10,37,42])  # 在s中添加多項  
  40. 使用remove()可以删除一項:  
  41. t.remove('H')  
  42. len(s)  
  43. set 的長度  
  44. x in s  
  45. 測試 x 是否是 s 的成員  
  46. x not in s  
  47. 測試 x 是否不是 s 的成員  
  48. s.issubset(t)  
  49. s <= t  
  50. 測試是否 s 中的每一個元素都在 t 中  
  51. s.issuperset(t)  
  52. s >= t  
  53. 測試是否 t 中的每一個元素都在 s 中  
  54. s.union(t)  
  55. s | t  
  56. 傳回一個新的 set 包含 s 和 t 中的每一個元素  
  57. s.intersection(t)  
  58. s & t  
  59. 傳回一個新的 set 包含 s 和 t 中的公共元素  
  60. s.difference(t)  
  61. s - t  
  62. 傳回一個新的 set 包含 s 中有但是 t 中沒有的元素  
  63. s.symmetric_difference(t)  
  64. s ^ t  
  65. 傳回一個新的 set 包含 s 和 t 中不重複的元素  
  66. s.copy()  
  67. 傳回 set “s”的一個淺複制  
  68. 請注意:union(), intersection(), difference() 和 symmetric_difference() 的非運算符(non-operator,就是形如 s.union()這樣的)版本将會接受任何 iterable 作為參數。相反,它們的運算符版本(operator based counterparts)要求參數必須是 sets。這樣可以避免潛在的錯誤,如:為了更可讀而使用 set('abc') & 'cbs' 來替代 set('abc').intersection('cbs')。從 2.3.1 版本中做的更改:以前所有參數都必須是 sets。  
  69. 另外,Set 和 ImmutableSet 兩者都支援 set 與 set 之間的比較。兩個 sets 在也隻有在這種情況下是相等的:每一個 set 中的元素都是另一個中的元素(二者互為subset)。一個 set 比另一個 set 小,隻有在第一個 set 是第二個 set 的 subset 時(是一個 subset,但是并不相等)。一個 set 比另一個 set 打,隻有在第一個 set 是第二個 set 的 superset 時(是一個 superset,但是并不相等)。  
  70. 子 set 和相等比較并不産生完整的排序功能。例如:任意兩個 sets 都不相等也不互為子 set,是以以下的運算都會傳回 False:a<b, a==b, 或者a>b。是以,sets 不提供 __cmp__ 方法。  
  71. 因為 sets 隻定義了部分排序功能(subset 關系),list.sort() 方法的輸出對于 sets 的清單沒有定義。  
  72. 運算符  
  73.    運算結果  
  74. hash(s)  
  75.    傳回 s 的 hash 值  
  76. 下面這個表列出了對于 Set 可用二對于 ImmutableSet 不可用的運算:  
  77. 運算符(voperator)  
  78. 等價于  
  79. 運算結果  
  80. s.update(t)  
  81. s |= t  
  82. 傳回增加了 set “t”中元素後的 set “s”  
  83. s.intersection_update(t)  
  84. s &= t  
  85. 傳回隻保留含有 set “t”中元素的 set “s”  
  86. s.difference_update(t)  
  87. s -= t  
  88. 傳回删除了 set “t”中含有的元素後的 set “s”  
  89. s.symmetric_difference_update(t)  
  90. s ^= t  
  91. 傳回含有 set “t”或者 set “s”中有而不是兩者都有的元素的 set “s”  
  92. s.add(x)  
  93. 向 set “s”中增加元素 x  
  94. s.remove(x)  
  95. 從 set “s”中删除元素 x, 如果不存在則引發 KeyError  
  96. s.discard(x)  
  97. 如果在 set “s”中存在元素 x, 則删除  
  98. s.pop()  
  99. 删除并且傳回 set “s”中的一個不确定的元素, 如果為空則引發 KeyError  
  100. s.clear()  
  101. 删除 set “s”中的所有元素  
  102. 請注意:非運算符版本的 update(), intersection_update(), difference_update()和symmetric_difference_update()将會接受任意 iterable 作為參數。從 2.3.1 版本做的更改:以前所有參數都必須是 sets。  
  103. 還請注意:這個子產品還包含一個 union_update() 方法,它是 update() 方法的一個别名。包含這個方法是為了向後相容。程式員們應該多使用 update() 方法,因為這個方法也被内置的 set() 和 frozenset() 類型支援。  

【題目:050】| 說說decorator的用法和它的應用場景,如果可以的話,寫一個decorator

[python]  view plain  copy

  1. 所謂裝飾器就是把函數包裝一下,為函數添加一些附加功能,裝飾器就是一個函數,參數為被包裝的函數,傳回包裝後的函數:  
  2. def d(fp):  
  3.     def _d(*arg, **karg):  
  4.         print "do sth before fp.."  
  5.         r= fp(*arg, **karg)  
  6.         print "do sth after fp.."  
  7.         return r  
  8.     return _d  
  9. @d  
  10. def f():  
  11.     print "call f"  
  12. #上面使用@d來表示裝飾器和下面是一個意思  
  13. #f = d(f)  
  14. f()#調用f  

【題目:051】 | 寫一個類,并讓它盡可能多的支援操作符 [python]  view plain  copy

  1. class Array:  
  2.     __list = []  
  3.     def __init__(self):  
  4.         print "constructor"  
  5.     def __del__(self):  
  6.         print "destructor"  
  7.     def __str__(self):  
  8.         return "this self-defined array class"  
  9.     def __getitem__(self, key):  
  10.         return self.__list[key]  
  11.     def __len__(self):  
  12.         return len(self.__list)  
  13.     def Add(self, value):  
  14.         self.__list.append(value)  
  15.     def Remove(self, index):  
  16.         del self.__list[index]  
  17.     def DisplayItems(self):  
  18.         print "show all items----"  
  19.         for item in self.__list:  
  20.             print item  
  21. arr = Array()   #constructor  
  22. print arr    #this self-defined array class  
  23. print len(arr)   #0  
  24. arr.Add(1)  
  25. arr.Add(2)  
  26. arr.Add(3)  
  27. print len(arr)   #3  
  28. print arr[0]   #1  
  29. arr.DisplayItems()  
  30. #show all items----  
  31. #1  
  32. #2  
  33. #3  
  34. arr.Remove(1)  
  35. arr.DisplayItems()  
  36. #show all items----  
  37. #1  
  38. #3  
  39. #destructor  

【題目:052】| 說一說你見過比較cool的python實作

[python]  view plain  copy

  1. cool的概念,角度不同,看法可能也就不同,個人覺得更Pythonic的代碼就是最酷的代碼。  

【題目:053】 | Python如何實作單例模式 [python]  view plain  copy

  1. #-*- encoding=utf-8 -*-  
  2. print '----------------------方法1--------------------------'  
  3. #方法1,實作__new__方法  
  4. #并在将一個類的執行個體綁定到類變量_instance上,  
  5. #如果cls._instance為None說明該類還沒有執行個體化過,執行個體化該類,并傳回  
  6. #如果cls._instance不為None,直接傳回cls._instance  
  7. class Singleton(object):  
  8.     def __new__(cls, *args, **kw):  
  9.         if not hasattr(cls, '_instance'):  
  10.             orig = super(Singleton, cls)  
  11.             cls._instance = orig.__new__(cls, *args, **kw)  
  12.         return cls._instance  
  13. class MyClass(Singleton):  
  14.     a = 1  
  15. one = MyClass()  
  16. two = MyClass()  
  17. two.a = 3  
  18. print one.a  
  19. #3  
  20. #one和two完全相同,可以用id(), ==, is檢測  
  21. print id(one)  
  22. #29097904  
  23. print id(two)  
  24. #29097904  
  25. print one == two  
  26. #True  
  27. print one is two  
  28. #True  
  29. print '----------------------方法2--------------------------'  
  30. #方法2,共享屬性;所謂單例就是所有引用(執行個體、對象)擁有相同的狀态(屬性)和行為(方法)  
  31. #同一個類的所有執行個體天然擁有相同的行為(方法),  
  32. #隻需要保證同一個類的所有執行個體具有相同的狀态(屬性)即可  
  33. #所有執行個體共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict)  
  34. #可參看:http://code.activestate.com/recipes/66531/  
  35. class Borg(object):  
  36.     _state = {}  
  37.     def __new__(cls, *args, **kw):  
  38.         ob = super(Borg, cls).__new__(cls, *args, **kw)  
  39.         ob.__dict__ = cls._state  
  40.         return ob  
  41. class MyClass2(Borg):  
  42.     a = 1  
  43. one = MyClass2()  
  44. two = MyClass2()  
  45. #one和two是兩個不同的對象,id, ==, is對比結果可看出  
  46. two.a = 3  
  47. print one.a  
  48. #3  
  49. print id(one)  
  50. #28873680  
  51. print id(two)  
  52. #28873712  
  53. print one == two  
  54. #False  
  55. print one is two  
  56. #False  
  57. #但是one和two具有相同的(同一個__dict__屬性),見:  
  58. print id(one.__dict__)  
  59. #30104000  
  60. print id(two.__dict__)  
  61. #30104000  
  62. print '----------------------方法3--------------------------'  
  63. #方法3:本質上是方法1的更新(或者說進階)版  
  64. #使用__metaclass__(元類)的進階python用法  
  65. class Singleton2(type):  
  66.     def __init__(cls, name, bases, dict):  
  67.         super(Singleton2, cls).__init__(name, bases, dict)  
  68.         cls._instance = None  
  69.     def __call__(cls, *args, **kw):  
  70.         if cls._instance is None:  
  71.             cls._instance = super(Singleton2, cls).__call__(*args, **kw)  
  72.         return cls._instance  
  73. class MyClass3(object):  
  74.     __metaclass__ = Singleton2  
  75. one = MyClass3()  
  76. two = MyClass3()  
  77. two.a = 3  
  78. print one.a  
  79. #3  
  80. print id(one)  
  81. #31495472  
  82. print id(two)  
  83. #31495472  
  84. print one == two  
  85. #True  
  86. print one is two  
  87. #True  
  88. print '----------------------方法4--------------------------'  
  89. #方法4:也是方法1的更新(進階)版本,  
  90. #使用裝飾器(decorator),  
  91. #這是一種更pythonic,更elegant的方法,  
  92. #單例類本身根本不知道自己是單例的,因為他本身(自己的代碼)并不是單例的  
  93. def singleton(cls, *args, **kw):  
  94.     instances = {}  
  95.     def _singleton():  
  96.         if cls not in instances:  
  97.             instances[cls] = cls(*args, **kw)  
  98.         return instances[cls]  
  99.     return _singleton  
  100. @singleton  
  101. class MyClass4(object):  
  102.     a = 1  
  103.     def __init__(self, x=0):  
  104.         self.x = x  
  105. one = MyClass4()  
  106. two = MyClass4()  
  107. two.a = 3  
  108. print one.a  
  109. #3  
  110. print id(one)  
  111. #29660784  
  112. print id(two)  
  113. #29660784  
  114. print one == two  
  115. #True  
  116. print one is two  
  117. #True  
  118. one.x = 1  
  119. print one.x  
  120. #1  
  121. print two.x  
  122. #1  

【題目:054】| 如何用Python來發送郵件

[python]  view plain  copy

  1. # 可以使用smtplib标準庫。  
  2. # 以下代碼可以在支援SMTP監聽器的伺服器上執行。  
  3. import sys, smtplib  
  4. fromaddr = raw_input("From: ")  
  5. toaddrs  = raw_input("To: ").split(',')  
  6. print("Enter message, end with ^D:")  
  7. msg = ''  
  8. while 1:  
  9.     line = sys.stdin.readline()  
  10.     if not line:  
  11.         break  
  12. msg += line  
  13. # 發送郵件部分  
  14. server = smtplib.SMTP('localhost')  
  15. server.sendmail(fromaddr, toaddrs, msg)  
  16. server.quit()  

【題目:055】| Python自動連接配接ssh的代碼

[python]  view plain  copy

  1. #!/usr/bin/env python  
  2. #import the need library.  
  3. import pxssh  
  4. #machine details  
  5. hostname = ''  
  6. username = ''  
  7. password = ''  
  8. #command we want to send  
  9. command = 'ls -lart'  
  10. #function to connect  
  11. def connect(hostname, username, password, release):  
  12.     try:  
  13.         s = pxssh.pxssh()  
  14.         s.login(hostname, username, password, release)  
  15.         print s  
  16.         return s  
  17.     except Exception, e:  
  18.         print "[-] Error Connecting: " + str(e)  
  19. #func to send a command  
  20. def send_command(ssh_session, command):  
  21.     ssh_session.sendline(command)  
  22.     ssh_session.prompt()  
  23.     print ssh_session.before  
  24. #main()  
  25. if __name__ == "__main__":  
  26.     session = connect(hostname, username, password)  
  27.     send_command(session, command)  

或者用pexpect子產品

[python]  view plain  copy

  1. #!/usr/bin/env python  
  2. import pexpect  
  3. def ssh_cmd(ip, passwd, cmd):  
  4.     ret = -1  
  5.     ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))  
  6.     try:  
  7.         i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)  
  8.         if i == 0 :  
  9.             ssh.sendline(passwd)  
  10.         elif i == 1:  
  11.             ssh.sendline('yes\n')  
  12.             ssh.expect('password: ')  
  13.             ssh.sendline(passwd)  
  14.         ssh.sendline(cmd)  
  15.         res = ssh.read()  
  16.         print res  
  17.         ret = 0  
  18.     except pexpect.EOF:  
  19.         print "EOF"  
  20.         ssh.close()  
  21.         ret = -1  
  22.     except pexpect.TIMEOUT:  
  23.         print "TIMEOUT"  
  24.         ssh.close()  
  25.         ret = -2  
  26.     return ret  
  27. #main()  
  28. if __name__ == "__main__":  
  29.     ssh_cmd('127.0.0.1', 'password', 'ls -lart')  

【 題目:056】 | 介紹一下Python Date Time方面的類

[python]  view plain  copy

  1. 一.time子產品  
  2. time子產品提供各種操作時間的函數  
  3. 一般有兩種表示時間的方式:  
  4. 第一種: 是時間戳的方式(相對于1970.1.1 00:00:00以秒計算的偏移量),時間戳是惟一的  
  5. 第二種: 以數組的形式表示即(struct_time),共有九個元素,分别表示,同一個時間戳的struct_time會因為時區不同而不同  
  6. 二.datetime子產品  
  7. Python提供了多個内置子產品用于操作日期時間,像calendar,time,datetime。time子產品。  
  8. 相比于time子產品,datetime子產品的接口則更直覺、更容易調用。  
  9. datetime子產品定義了下面這幾個類:  
  10. datetime.date:表示日期的類。常用的屬性有year, month, day;  
  11. datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond;  
  12. datetime.datetime:表示日期時間。  
  13. datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。  
  14. datetime.tzinfo:與時區有關的相關資訊。  
  15. datetime中,表示日期時間的是一個datetime對象  
  16. datetime中提供了strftime方法,可以将一個datetime型日期轉換成字元串:  

【題目:057】| 寫一個簡單的Python socket程式設計

伺服器端程式:

[python]  view plain  copy

  1. # FileName: server.py  
  2. import socket  
  3. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  4. sock.bind(('localhost', 8001))  
  5. sock.listen(5)  
  6. while True:  
  7.     conn, addr = sock.accept()  
  8.     try:  
  9.         conn.settimeout(5)  
  10.         buff = conn.recv(1024)  
  11.         if buff == '1':  
  12.             conn.send('Hello, Client...')  
  13.         else:  
  14.             conn.send('Please, Go Out...')  
  15.     except socket.timeout:  
  16.         print 'Socket Time Out...'  
  17.     finally:  
  18.         conn.close()  

用戶端程式:

[python]  view plain  copy

  1. # FileName: client.py  
  2. import socket  
  3. import time  
  4. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  5. sock.connect(('localhost', 8001))  
  6. time.sleep(2)  
  7. sock.send('1')  
  8. print sock.recv(1024)  
  9. sock.close()  

在終端運作server.py,然後運作clien.py,會在終端列印“Hello, Client..."。

如果更改client.py的sock.send('1')為其它值在終端會列印“Please, Go Out...”。

更改time.sleep(2)為大于5的數值, 伺服器将會逾時。

【題目:058】| Tkinter的ToolTip控件

[python]  view plain  copy

  1. Tooltip控件是一個簡單,但非常有用的控件。它能夠為我們的軟體提供非常漂亮的提示資訊,提高軟體的可用性,給使用者比較好的體驗。  
  2. 假設現在有兩個按鈕,一個用來預覽吊線世系圖,一個用來預覽行轉。為了保持按鈕文本的簡潔,以及為按鈕尺寸所限。  
  3. 我們不能可能把這個按鈕的主要功能通過text屬性表述清楚,這個時候我們就可以用到tooltip控件了.  

【題目:059】 | 解釋一下python的and-or文法

[python]  view plain  copy

  1. 0 and * 不需要再考慮*是0還是1,結果是0  
  2. 1 and * 需要考慮*是0還是1來決定結果。  
  3. 1 or * 不需要考慮後面的*,結果為1  
  4. 0 or * 需要考慮後面的*來決定結果  
  5. 這個文法看起來類似于 C 語言中的 bool ? a : b 表達式。整個表達式從左到右進行演算,是以先進行 and 表達式的演算。 1 and 'first' 演算值為 'first',然後 'first' or 'second' 的演算值為 'first'。  
  6. 0 and 'first' 演算值為 False,然後 0 or 'second' 演算值為 'second'。  
  7. and-or主要是用來模仿 三目運算符 bool?a:b的,即當表達式bool為真,則取a否則取b。  
  8. and-or 技巧,bool and a or b 表達式,當 a 在布爾上下文中的值為假時,不會像 C 語言表達式 bool ? a : b 那樣工作。  

【題目:060】 | Python裡關于“堆”這種資料結構的子產品是哪個?“堆”有什麼優點和缺點

這個真沒有! 

【題目:061】| 實作一個stack

[python]  view plain  copy

  1. class Stack :  
  2.     def __init__( self ):  
  3.         ''''' Creates an empty stack. '''  
  4.         self._items = list()  
  5.     def isEmpty(self):  
  6.         ''''' Returns True if the stack is empty or False otherwise. '''  
  7.         return len(self) == 0  
  8.     def __len__(self):  
  9.         ''''' Returns the number of items in the stack. '''  
  10.         return len(self._items)  
  11.     def peek(self):  
  12.        ''''' Returns the top item on the stack without removing it. '''  
  13.        assert not self.isEmpty(), "Cannot peek at an empty stack"  
  14.        return self._items[-1]  
  15.     def pop(self):  
  16.         ''''' Removes and returns the top item on the stack. '''  
  17.         assert not self.isEmpty(), "Cannot pop from an empty stack"  
  18.         return self._items.pop()  
  19.     def push(self,item):  
  20.         ''''' Push an item onto the top of the stack. '''  
  21.         self._items.append( item )  

【題目:062】| 編寫一個簡單的ini檔案解釋器

db_config.ini

[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=evaluting_sys
[concurrent]
processor=20
      

示例代碼

import sys,os
import ConfigParser
def test(config_file_path):
    cf = ConfigParser.ConfigParser()
    cf.read(config_file_path)

    s = cf.sections()
    print 'section:', s

    o = cf.options("baseconf")
    print 'options:', o

    v = cf.items("baseconf")
    print 'db:', v

    db_host = cf.get("baseconf", "host")
    db_port = cf.getint("baseconf", "port")
    db_user = cf.get("baseconf", "user")
    db_pwd = cf.get("baseconf", "password")

    print db_host, db_port, db_user, db_pwd

    cf.set("baseconf", "db_pass", "123456")
    cf.write(open("config_file_path", "w"))
if __name__ == "__main__":
    test("../conf/db_config.ini")      

【題目:063】| 現有N個純文字格式的英文檔案,實作一種檢索方案,即做一個小搜尋引擎

【題目:064】| src = "security/afafsff/?ip=123.4.56.78&id=45",請寫一段代碼用正則比對出IP

[python]  view plain  copy

  1. import re  
  2. src = "security/afafsff/?ip=123.4.56.78&id=45"  
  3. m = re.search('ip=(\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3})', src, re.S)  # re.S 改變'.'的行為  
  4. print m.group(1)  
  5. # 輸出結果  
  6. >>>   
  7. 123.4.56.78  

【題目:064】|  已知倉庫中有若幹商品,以及相應庫存,類似:

襪子,10

鞋子,20

拖鞋,30

項鍊,40

要求随機傳回一種商品,要求商品被傳回的機率與其庫存成正比。請描述實作的思路或者直接寫一個實作的函數

[python]  view plain  copy

  1. # -*- coding: utf-8 -*-   
  2. import random  
  3. Wa_Zhi     = ['WZ'] * 100  
  4. Xie_Zi     = ['XZ'] * 200  
  5. Tuo_Xie    = ['TX'] * 300  
  6. Xiang_Lian = ['XL'] * 400  
  7. All_Before = Wa_Zhi + Xie_Zi + Tuo_Xie + Xiang_Lian  
  8. All_After  = random.sample(All_Before, 100)  
  9. print All_After.count('WZ')  
  10. print All_After.count('XZ')  
  11. print All_After.count('TX')  
  12. print All_After.count('XL')  
  13. #輸出結果,大緻滿足需求1: 2: 3: 4的比例  
  14. >>>   
  15. 9  
  16. 19  
  17. 32  
  18. 40