Python面試題彙總
拿網絡上關于Python的面試題彙總了,給出了自認為合理的答案,有些題目不錯,可以從中學到點什麼,答案如不妥,請指正......
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
【題目:001】| 說說你對zen of python的了解,你有什麼辦法看到它?
Python之禅,Python秉承一種獨特的簡潔和可讀行高的文法,以及高度一緻的程式設計模式,符合“大腦思維習慣”,使Python易于學習、了解和記憶。Python同時采用了一條極簡主義的設計理念,了解完整的Python哲學理念,可以在任何一個Python互動解釋器中鍵入import this指令,這是Python隐藏的一個彩蛋:描繪了一系列Python設計原則。如今已是Python社群内流行的行話"EIBTI",明了勝于晦澀這條規則的簡稱. 在Python的思維方式中,明了勝于晦澀,簡潔勝于複雜。
[python] view plain copy
- >>> import this
- The Zen of Python, by Tim Peters
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than *right* now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
【題目:002】| 說說你對pythonic的看法,嘗試解決下面的小問題
#簡潔,明了,嚴謹,靈活
[python] view plain copy
- #交換兩個變量值
- a,b = b,a
- #去掉list中的重複元素
- old_list = [1,1,1,3,4]
- new_list = list(set(old_list))
- #翻轉一個字元串
- s = 'abcde'
- ss = s[::-1]
- #用兩個元素之間有對應關系的list構造一個dict
- names = ['jianpx', 'yue']
- ages = [23, 40]
- m = dict(zip(names,ages))
- #将數量較多的字元串相連,如何效率較高,為什麼
- fruits = ['apple', 'banana']
- result = ''.join(fruits)
- #python字元串效率問題之一就是在連接配接字元串的時候使用‘+’号,例如 s = ‘s1’ + ‘s2’ + ‘s3’ + ...+’sN’,總共将N個字元串連接配接起來, 但是使用+号的話,python需要申請N-1次記憶體空間, 然後進行字元串拷貝。原因是字元串對象PyStringObject在python當中是不可變 對象,是以每當需要合并兩個字元串的時候,就要重新申請一個新的記憶體空間 (大小為兩個字元串長度之和)來給這個合并之後的新字元串,然後進行拷貝。 是以用+号效率非常低。建議在連接配接字元串的時候使用字元串本身的方法 join(list),這個方法能提高效率,原因是它隻是申請了一次記憶體空間, 因為它可以周遊list中的元素計算出總共需要申請的記憶體空間的大小,一次申請完。
【題目:003 】| 你調試python代碼的方法有哪些?
[python] view plain copy
- 具體IDE都有調試,比如:IDLE, Eclipse+Pydev都可以設定斷點調試。
- pdb子產品也可以做調試。
- 還有PyChecker和Pylint
- PyChecker是一個python代碼的靜态分析工具,它可以幫助查找python代碼的bug, 會對代碼的複雜度和格式提出警告
- Pylint 是另外一個工具可以進行coding standard檢查。
【題目:004 】| 你在github上都fork過哪些python庫,列舉一下你經常使用的,每個庫用一句話描述下其功能
[python] view plain copy
- http://rogerdudler.github.io/git-guide/index.zh.html #關于git簡明指南
- http://www.zhihu.com/question/20070065 #關于git的BBS
- http://www.techug.com/githug-for-designer #關于github的
【題目:005 】| 什麼是GIL?
[python] view plain copy
- 什麼是GIL(Global Interpreter Lock)全局解釋器鎖? 簡單地說就是:
- 每一個interpreter程序,隻能同時僅有一個線程來執行, 獲得相關的鎖, 存取相關的資源.
- 那麼很容易就會發現,如果一個interpreter程序隻能有一個線程來執行,
- 多線程的并發則成為不可能, 即使這幾個線程之間不存在資源的競争.
- 從理論上講,我們要盡可能地使程式更加并行, 能夠充分利用多核的功能.
【 題目:006】 | 什麼是元類(meta_class)?
[python] view plain copy
- 元類就是用來建立類的“東西”
- 詳情操作: http://blog.jobbole.com/21351/
【 題目:007 】| 對比一下dict中items與iteritems?
[python] view plain copy
- >>> D = {'a':1,'b':2,'c':3,'d':4}
- >>> D.items() #一次性取出所有
- [('a', 1), ('c', 3), ('b', 2), ('d', 4)]
- >>> D.iteritems() #疊代對象,每次取出一個。用for循環周遊出來;
- <dictionary-itemiterator object at 0x00000000026243B8>
- >>> for i in D.iteritems():
- ... print i,
- ...
- ('a', 1) ('c', 3) ('b', 2) ('d', 4)
- >>> for k,v in D.iteritems():
- ... print k,
- ...
- a c b d
- 總結:
- 1. 一般iteritems()疊代的辦法比items()要快,特别是資料庫比較大時。
- 2. 在Python3中一般取消前者函數
【 題目:008 】| 是否遇到過python的子產品間循環引用的問題,如何避免它?
[python] view plain copy
- 這是代碼結構設計的問題,子產品依賴和類依賴
- 如果老是覺得碰到循環引用,很可能是子產品的分界線劃錯地方了。可能是把應該在一起的東西硬拆開了,可能是某些職責放錯地方了,可能是應該抽象的東西沒抽象
- 總之微觀代碼規範可能并不能幫到太多,重要的是更宏觀的劃分子產品的經驗技巧,推薦uml,腦圖,白闆等等圖形化的工具先梳理清楚整個系統的總體結構和職責分工
- 采取辦法,從設計模式上來規避這個問題,比如:
- 1. 使用 “__all__” 白名單開放接口
- 2. 盡量避免 import
【 題目:009 】| 有用過with statement嗎?它的好處是什麼?
[python] view plain copy
- >>> with open('text.txt') as myfile:
- ... while True:
- ... line = myfile.readline()
- ... if not line:
- ... break
- ... print line,
- # with語句使用所謂的上下文管理器對代碼塊進行包裝,允許上下文管理器實作一些設定和清理操作。
- # 例如:檔案可以作為上下文管理器使用,它們可以關閉自身作為清理的一部分。
- # NOTE:在PYTHON2.5中,需要使用from __future__ import with_statement進行with語句的導入
【題目:010】 | 用Python生成指定長度的斐波那契數列
[python] view plain copy
- def fibs(x):
- result = [0, 1]
- for index in range(x-2):
- result.append(result[-2]+result[-1])
- return result
- if __name__=='__main__':
- num = input('Enter one number: ')
- print fibs(num)
【題目:011】 | Python裡如何生産随機數
[python] view plain copy
- >>> import random
- >>> random.random()
- 0.29495314937268713
- >>> random.randint(1,11)
- 8
- >>> random.choice(range(11))
- 3
【題目:012】 | Python裡如何反序的疊代一個序列
[python] view plain copy
- 如果是一個list, 最快的解決方案是:
- list.reverse()
- try:
- for x in list:
- “do something with x”
- finally:
- list.reverse()
- 如果不是list, 最通用但是稍慢的解決方案是:
- for i in range(len(sequence)-1, -1, -1):
- x = sequence[i]
【題目:013】 | Python中如何定義一個函數
[python] view plain copy
- def func(arg, *args, **kwagrs): #普通函數
- func_body
- return
- lambda x: x **2 #匿名函數
【題目:014】 | Python比對HTML tag的時候,<.*>和<.*?>有什麼差別
[python] view plain copy
- import re
- s = ‘<html><head><title>Title</title>’
- print(re.match(‘<.*>’, s).group())
- 會傳回一個比對<html><head><title>Title</title>而不是<html>
- 而
- import re
- s = ‘<html><head><title>Title</title>’
- print(re.match(‘<.*?>’, s).group())
- 則會傳回<html>
- <.*>這種比對稱作貪心比對 <.*?>稱作非貪心比對
【題目:015】 | Python裡面search()和match()的差別 [python] view plain copy
- >>> import re
- >>> re.match(r'python','Programing Python, should be pythonic')
- >>> obj1 = re.match(r'python','Programing Python, should be pythonic') #傳回None
- >>> obj2 = re.search(r'python','Programing Python, should be pythonic') #找到pythonic
- >>> obj2.group()
- 'python'
- #re.match隻比對字元串的開始,如果字元串開始不符合正規表達式,則比對失敗,函數傳回None;
- #re.search比對整個字元串,直到找到一個比對。
【題目:016】 | Python程式中文輸出問題怎麼解決
[python] view plain copy
- 在Python3中,對中文進行了全面的支援,但在Python2.x中需要進行相關的設定才能使用中文。否則會出現亂碼。
- Python預設采取的ASCII編碼,字母、标點和其他字元隻使用一個位元組來表示,但對于中文字元來說,一個位元組滿足不了需求。
- 為了能在計算機中表示所有的中文字元,中文編碼采用兩個位元組表示。如果中文編碼和ASCII混合使用的話,就會導緻解碼錯誤,進而才生亂碼。
- 解決辦法:
- 互動式指令中:一般不會出現亂碼,無需做處理
- py腳本檔案中:跨字元集必須做設定,否則亂碼
- 1. 首先在開頭一句添加:
- # coding = utf-8
- # 或
- # coding = UTF-8
- # 或
- # -*- coding: utf-8 -*-
- 2. 其次需将檔案儲存為UTF-8的格式!
- 3. 最後: s.decode('utf-8').encode('gbk')
【題目:017】 | 什麼是lambda函數
[python] view plain copy
- 函數使用:
- 1. 代碼塊重複,這時候必須考慮到函數,降低程式的備援度
- 2. 代碼塊複雜,這時候必須考慮到函數,降低程式的複雜度
- Python有兩種函數,一種是def定義,一種是lambda函數()
- 當程式代碼很短,且該函數隻使用一次,為了程式的簡潔,及節省變量記憶體占用空間,引入了匿名函數這個概念
- >>> nums = range(2,20)
- >>> for i in nums:
- nums = filter(lambda x:x==i or x % i,nums)
- >>> nums
- [2, 3, 5, 7, 11, 13, 17, 19]
【題目:018】 | Python裡面如何實作tuple和list的轉換
[python] view plain copy
- #From list to Tuple
- tuple(a_list)
- #From Tuple to List
- def to_list(t):
- return [i if not isinstance(i,tuple) else to_list(i) for i in t]
【題目:019】 | 請寫出一段Python代碼實作删除一個list裡面的重複元素
[python] view plain copy
- >>> L1 = [4,1,3,2,3,5,1]
- >>> L2 = []
- >>> [L2.append(i) for i in L1 if i not in L2]
- >>> print L2
- [4, 1, 3, 2, 5]
【題目:020】 | Python是如何進行類型轉換的
[python] view plain copy
- >>> int('1234') # 将數字型字元串轉為整形
- 1234
- >>> float(12) # 将整形或數字字元轉為浮點型
- 12.0
- >>> str(98) # 将其他類型轉為字元串型
- '98'
- >>> list('abcd') # 将其他類型轉為清單類型
- ['a', 'b', 'c', 'd']
- >>> dict.fromkeys(['name','age']) # 将其他類型轉為字典類型
- {'age': None, 'name': None}
- >>> tuple([1, 2, 3, 4]) # 将其他類型轉為元祖類型
- (1, 2, 3, 4)
詳細轉換總結如下:
[python] view plain copy
- 函數 描述
- int(x [,base]) 将x轉換為一個整數
- long(x [,base] ) 将x轉換為一個長整數
- float(x) 将x轉換到一個浮點數
- complex(real [,imag]) 建立一個複數
- str(x) 将對象 x 轉換為字元串
- repr(x) 将對象 x 轉換為表達式字元串
- eval(str) 用來計算在字元串中的有效Python表達式,并傳回一個對象
- tuple(s) 将序列 s 轉換為一個元組
- list(s) 将序列 s 轉換為一個清單
- set(s) 轉換為可變集合
- dict(d) 建立一個字典。d 必須是一個序列 (key,value)元組。
- frozenset(s) 轉換為不可變集合
- chr(x) 将一個整數轉換為一個字元
- unichr(x) 将一個整數轉換為Unicode字元
- ord(x) 将一個字元轉換為它的整數值
- hex(x) 将一個整數轉換為一個十六進制字元串
- oct(x) 将一個整數轉換為一個八進制字元串
【題目:021】| 如何知道一個Python對象的類型
[python] view plain copy
- >>> type([]);type('');type(0);type({});type(0.0);type((1,))
- <type 'list'>
- <type 'str'>
- <type 'int'>
- <type 'dict'>
- <type 'float'>
- <type 'tuple'>
【題目:022】| Python裡面如何拷貝一個對象
[python] view plain copy
- 切片S[:] # 注不能應用于字典
- 深淺寶貝 # 能應用于所有序列和字典
- 1. 淺拷貝D.copy()方法
- 2. 深拷貝deepcopy(D)方法
【題目:023】 | Python中pass語句的作用是什麼 [python] view plain copy
- pass語句什麼也不做,一般作為占位符或者建立占位程式
【題目:024】 | 寫一段程式逐行讀入一個文本檔案,并在螢幕上列印出來 [python] view plain copy
- f = open(filename)
- while True:
- line = f.readline()
- if not line: break
- print(line)
- f.close()
【題目:025】 | 如何用Python删除一個檔案 [python] view plain copy
- import os
- os.remove(filename)
【題目:026】 | Python代碼得到清單list的交集與差集 [python] view plain copy
- >>> list1 = [1, 3, 4, 6]
- >>> list2 = [1, 2, 3, 4]
- >>> [i for i in list1 if i not in list2]
- [6]
- >>> [i for i in list1 if i in list2]
- [1, 3, 4]
【題目:027】 | Python是如何進行記憶體管理的
[python] view plain copy
- python内部使用引用計數,來保持追蹤記憶體中的對象,Python内部記錄了對象有多少個引用,即引用計數,當對象被建立時就建立了一個引用計數,當對象不再需要時,這個對象的引用計數為0時,它被垃圾回收。所有這些都是自動完成,不需要像C一樣,人工幹預,進而提高了程式員的效率和程式的健壯性。
【題目:028】 | 介紹一下Python下range()函數的用法
[python] view plain copy
- >>> range(10)
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- >>> range(1, 10)
- [1, 2, 3, 4, 5, 6, 7, 8, 9]
- >>> range(0, 9, 2)
- [0, 2, 4, 6, 8]
- >>> range(99,0,-10)
- [99, 89, 79, 69, 59, 49, 39, 29, 19, 9]
- 相差別的是xrange(),每次隻取出一個疊代對象,如果是資料量比較大時,效率較高
- 在Python3中,沒有xrange()函數,其功能放在了range()函數上
【題目:029】| Python異常處理介紹一下
[python] view plain copy
- 程式中出現異常情況時就需要異常處理。比如當你打開一個不存在的檔案時。當你的程式中有
- 一些無效的語句時,Python會提示你有錯誤存在。下面是一個拼寫錯誤的例子,print寫成了Print
- 下面是異常最常見的幾種角色
- 1. 錯誤處理
- >>>可以在程式代碼中捕捉和相應錯誤,或者忽略已發生的異常。
- >>>如果忽略錯誤,PYTHON預設的異常處理行為将啟動:停止程式,列印錯誤資訊。
- >>>如果不想啟動這種預設行為,就用try語句來捕捉異常并從異常中恢複。
- 2. 事件通知
- >>>異常也可用于發出有效狀态的信号,而不需在程式間傳遞結果标志位。或者刻意對其進行測試
- 3. 特殊情況處理
- >>>有時,發生了某種很罕見的情況,很難調整代碼區處理。通常會在異常進行中處理,進而省去應對特殊情況的代碼
- 4. 終止行為
- >>>try/finally語句可確定一定會進行需要的結束運算,無論程式是否有異常
- 5. 非正常控制流程
【題目:030】 | 介紹一下Python中的filter方法 [python] view plain copy
- filter就像map,reduce,apply,zip等都是内置函數,用C語言實作,具有速度快,功能強大等
- 優點。
- 用于過濾與函數func()不比對的值, 類似于SQL中select value != 'a'
- 相當于一個疊代器,調用一個布爾函數func來疊代seq中的每個元素,傳回一個是bool_seq返
- 回為True的序列
- >>>第一個參數: function or None, 函數或None
- >>>第二個參數: sequence,序列
【題目:031】 | 介紹一下except的用法和作用 [python] view plain copy
- try/except: 捕捉由PYTHON自身或寫程式過程中引發的異常并恢複
- except: 捕捉所有其他異常
- except name: 隻捕捉特定的異常
- except name, value: 捕捉異常及格外的資料(執行個體)
- except (name1,name2) 捕捉列出來的異常
- except (name1,name2),value: 捕捉任何列出的異常,并取得額外資料
- else: 如果沒有引發異常就運作
- finally: 總是會運作此處代碼
【題目:032】 | 如何用Python來進行查詢和替換一個文本字元串
[python] view plain copy
- >>> words = 'Python is a very funny language!'
- >>> words.find('Python') # 傳回的為0或正數時,為其索引号
- >>> words.find('is')
- 7
- >>> words.find('dafa') # 傳回-1表示查找失敗
- -1
- >>> words.replace('Python', 'Perl') # replace()替換
- 'Perl is a very funny language!'
【題目:033】 | Python如何copy一個檔案
[python] view plain copy
- import shutil
- shutil.copyfile('a.py', 'copy_a.py')
【題目:034】| Python判斷目前使用者是否是root
[python] view plain copy
- import os
- if os.getuid() != 0: # root賬号的uid=0
- print os.getuid()
- print 'Should run as root account'
- else:
- print 'Hello, Root!'
【題目:035】 | 用Python寫一個for循環的例子
[python] view plain copy
- for循環可以周遊序列(清單,字元串,元祖),range()及疊代對象,如xrange()
- names = ['Alice', 'Betty', 'Fred', 'Tom']
- for index, name in enumerate(names):
- print 'index:',index,'=>', name
- # 輸出結果
- index: 0 => Alice
- index: 1 => Betty
- index: 2 => Fred
- index: 3 => Tom
【題目:036】 | 介紹一下Python中webbrowser的用法
[python] view plain copy
- webbrowser子產品提供了一個進階接口來顯示基于Web的文檔,大部分情況下隻需要簡單的調用open()方法。
- webbrowser定義了如下的異常:exception webbrowser.Error, 當浏覽器控件發生錯誤是會抛出這個異常
- webbrowser有以下方法:
- webbrowser.open(url[, new=0[, autoraise=1]])
- 這個方法是在預設的浏覽器中顯示url, 如果new = 0, 那麼url會在同一個浏覽器視窗下打開,如果new = 1, 會打開一個新的視窗,如果new = 2, 會打開一個新的tab, 如果autoraise = true, 視窗會自動增長。
- webbrowser.open_new(url)
- 在預設浏覽器中打開一個新的視窗來顯示url, 否則,在僅有的浏覽器視窗中打開url
- webbrowser.open_new_tab(url)
- 在預設浏覽器中當開一個新的tab來顯示url, 否則跟open_new()一樣
- webbrowser.get([name]) 根據name傳回一個浏覽器對象,如果name為空,則傳回預設的浏覽器
- webbrowser.register(name, construtor[, instance])
- 注冊一個名字為name的浏覽器,如果這個浏覽器類型被注冊就可以用get()方法來擷取。
【題目:037】 | 默寫盡可能多的str對象的方法
[python] view plain copy
- #方法 #描述
- -------------------------------------------------------------------------------------------------
- S.capitalize() #傳回首字母大寫的字元串的副本
- S.center(width[,fillchar]) #傳回一個長度為max(len(S),width),S居中,兩側fillchar填充
- S.count(sub[,start[,end]]) #計算子字元串sub的出現次數,可将搜尋範圍限制為S[start:end]
- S.decode([encoding[,error]]) #傳回使用給定編碼方式的字元串的解碼版本,由error指定錯誤處理方式
- S.endswith(suffix[start[,end]]) #檢查S是否以suffix結尾,可給定[start:end]來選擇比對的範圍
- S.expandtabs([tabsize]) #傳回字元串的副本,其中tab字元會使用空格進行擴充,可選擇tabsize
- S.find(sun[,start[,end]]) #傳回子字元串sub的第一個索引,不存在則為-1,可選擇搜尋範圍
- S.index(sub[,start[,end]]) #傳回子字元串sub的第一個索引,不存在則引發ValueError異常.
- S.isalnum() #檢查字元串是否由字母或數字字元組成
- S.isalpha() #檢查字元串是否由字母字元組成
- S.isdigit() #檢查字元串是否由數字字元組成
- S.islower() #檢查字元串是否由小寫字母組成
- S.isspace() #檢查字元串是否由空格組成
- S.istitle() #檢查字元串時候首字母大寫
- S.isupper() #檢查字元串是否由大寫字母組成
- S.join(sequence) #傳回其中sequence的字元串元素由S連接配接的字元串
- S.ljust(width[,fillchar]) #傳回S副本左對齊的字元串,長度max(len(S),W),右側fillchar填充
- S.lower() #傳回所有字元串都為小寫的副本
- S.lstrip([char]) #向左移除所有char,預設移除(空格,tab,\n)
- S.partition(seq) #在字元串中搜尋seq并傳回
- S.replace(old,new[,max]) #将new替換olad,最多可替換max次
- S.rfind(sub[,start[,end]]) #傳回sub所在的最後一個索引,不存在則為-1,可定搜尋範圍S[start:end]
- S.rindex(sub[,start[,end]]) #傳回sub所在的最後一個索引,不存在則會引發ValueError異常。
- S.rjust(width[,fillchar]) #傳回S副本右對齊的字元串,長度max(len(S),W),左側fillchar填充
- S.rpartition(seq) #同Partition,但從右側開始查找
- S.rstip([char]) #向右移除所有char,預設移除(空格,tab,\n)
- S.rsplit(sep[,maxsplit]) #同split,但是使用maxsplit時是從右往左進行計數
- S.split(sep[,maxsplit]) #使用sep做為分割符,可使用maxsplit指定最大切分數
- S.zfill(width) #在S的左側以0填充width個字元
- S.upper() #傳回S的副本,所有字元大寫
- S.splitlines([keepends]) #傳回S中所有行的清單,可選擇是否包括換行符
- S.startswith(prefix[,start[,end]]) #檢查S是否以prefix開始,可用[start,end]來定義範圍
- S.strip([chars]) #移除所有字元串中含chars的字元,預設移除(空格,tab,\n)
- S.swapcase() #傳回S的副本,所有大小寫交換
- S.title() #傳回S的副本,所有單詞以大寫字母開頭
- S.translate(table[,deletechars]) #傳回S的副本,所有字元都使用table進行的轉換,可選擇删除出現在deletechars中的所有字元
【題目:038】 | 現在有一個dict對象adict,裡面包含了一百萬個元素,查找其中的某個元素的平均需要多少次比較 [python] view plain copy
- O(1) 哈希字典,快速查找,鍵值映射,鍵唯一!
【題目:039】 | 有一個list對象alist,裡面的所有元素都是字元串,編寫一個函數對它實作一個大小寫無關的排序 [python] view plain copy
- words = ['This','is','a','dog','!']
- words.sort(key=lambda x:x.lower())
- print words
- #輸出結果
- >>>
- ['!', 'a', 'dog', 'is', 'This']
【題目:040】 | 有一個排好序地list對象alist,查找其中是否有某元素a [python] view plain copy
- alist = ['a','s','d','f']
- try:
- alist.index('a')
- print 'Find it.'
- except ValueError:
- print 'Not Found.'
【題目:041】 | 請用Python寫一個擷取使用者輸入數字,并根據數字大小輸出不同資訊的腳本 [python] view plain copy
- num = input('Enter number: ')
- if num > 100:
- print 'The number is over 100'
- elif 0 < num <= 100:
- print 'The number is between 0~100'
- elif num < 0:
- print 'The number is negative.'
- else:
- print 'Not a number'
【題目:042】 | 打亂一個排好序的list對象alist [python] view plain copy
- # random子產品中的shuffle(洗牌函數)
- import random
- alist = [1, 2, 3, 4]
- random.shuffle(alist)
- print alist
【題目:043】 | 有二維的list對象alist,假定其中的所有元素都具有相同的長度,寫一段程式根據元素的第二個元素排序 [python] view plain copy
- def sort_lists(lists, sord, idx):
- if sord == 'desc':
- lists.sort(key=lambda x:x[idx], reverse=True)
- else:
- lists.sort(key=lambda x:x[idx])
- return lists
- lists = [['cd','ab'],['ef','ac']]
- sort_lists(lists,'desc',1)
- print lists
- # 輸出結果
- >>>
- [['ef', 'ac'], ['cd', 'ab']]
【題目:044】 | inspect子產品有什麼用 [python] view plain copy
- inspect子產品提供了一系列函數用于幫助使用自省。
- 檢查對象類型
- is{module|class|function|method|builtin}(obj): 檢查對象是否為子產品、類、函數、方法、内建函數或方法。
- isroutine(obj): 用于檢查對象是否為函數、方法、内建函數或方法等等可調用類型。
- 擷取對象資訊
- getmembers(object[, predicate]): 這個方法是dir()的擴充版,它會将dir()找到的名字對應的屬性一并傳回。
- getmodule(object): 它傳回object的定義所在的子產品對象。
- get{file|sourcefile}(object): 擷取object的定義所在的子產品的檔案名|源代碼檔案名(如果沒有則傳回None)。
- get{source|sourcelines}(object): 擷取object的定義的源代碼,以字元串|字元串清單傳回。
- getargspec(func): 僅用于方法,擷取方法聲明的參數,傳回元組,分别是(普通參數名的清單, *參數名, **參數名, 預設值元組)。
【題目:045】 | Python處理指令行參數示例代碼 [python] view plain copy
- # 最簡單、最原始的方法就是手動解析了
- import sys
- for arg in sys.argv[1:]:
- print(arg)
【題目:046】| 介紹一下Python getopt子產品
[python] view plain copy
- # getopt子產品是原來的指令行選項解析器,支援UNIX函數getopt()建立的約定。
- # 它會解析一個參數序列,如sys.argv,并傳回一個元祖序列和一個非選項參數序列。
- # 目前支援的選項文法包括短格式和長格式選項:-a, -bval, -b val, --noarg, --witharg=val, --witharg val。
- # 如果隻是簡單的指令行解析,getopt還是不錯的選擇。一個例子如下
- import sys
- import getopt
- try:
- options, remainder = getopt.getopt(sys.argv[1:], 'o:v', ['output=', 'verbose', 'version=',])
- except getopt.GetoptError as err:
- print 'ERROR:', err
- sys.exit(1)
- 總結下getopt的特點:1. getopt是從前到後解析 2. getopt不檢查額外參數的合法性,需要自行檢查 3. 短指令行和長指令行是分開解析的</span>
【題目:047】 | Python清單與元組的差別是什麼?分别在什麼情況下使用?
[python] view plain copy
- Python中清單和元祖都是序列,是以都能進行添加,删除,更新,切片等操作。但清單是可變對象,元祖是不可變對象。
- 元祖主要用于函數指派,字元串格式化等。但清單中的方法更多些,也是PYTHON中更常用的資料結構。
【題目:048】| 有一個長度是101的數組,存在1~100的數字,有一個是重複的,拿重複的找出來
[python] view plain copy
- # Python中,主要是拿count(i) ==2的找出來即可,再利用清單推導式
- >>> l = [1, 2, 3, 4, 2]
- >>> tmp = []
- >>> [tmp.append(i) for i in l if l.count(i) == 2]
- [None, None]
- >>> tmp
- [2, 2]
- >>> set(tmp)
- set([2])
【題目:049】| set是在哪個版本成為build-in types的?舉例說明,并說明為什麼當時選擇了set這種資料結構
[python] view plain copy
- python的set和其他語言類似, 是一個無序不重複元素集, 基本功能包括關系測試和消除重複元素. 集合對象還支援union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算.
- sets 支援 x in set, len(set),和 for x in set。作為一個無序的集合,sets不記錄元素位置或者插入點。是以,sets不支援 indexing, slicing, 或其它類序列(sequence-like)的操作。
- 下面來點簡單的小例子說明。
- >>> x = set('spam')
- >>> y = set(['h','a','m'])
- >>> x, y
- (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))
- 再來些小應用。
- >>> x & y # 交集
- set(['a', 'm'])
- >>> x | y # 并集
- set(['a', 'p', 's', 'h', 'm'])
- >>> x - y # 差集
- set(['p', 's'])
- 去除海量清單裡重複元素,用hash來解決也行,隻不過感覺在性能上不是很高,用set解決還是很不錯的,示例如下:
- >>> a = [11,22,33,44,11,22]
- >>> b = set(a)
- >>> b
- set([33, 11, 44, 22])
- >>> c = [i for i in b]
- >>> c
- [33, 11, 44, 22]
- 很酷把,幾行就可以搞定。
- 1.8 集合
- 集合用于包含一組無序的對象。要建立集合,可使用set()函數并像下面這樣提供一系列的項:
- s = set([3,5,9,10]) #建立一個數值集合
- t = set("Hello") #建立一個唯一字元的集合
- 與清單和元組不同,集合是無序的,也無法通過數字進行索引。此外,集合中的元素不能重複。例如,如果檢查前面代碼中t集合的值,結果會是:
- >>> t
- set(['H', 'e', 'l', 'o'])
- 注意隻出現了一個'l'。
- 集合支援一系列标準操作,包括并集、交集、差集和對稱差集,例如:
- a = t | s # t 和 s的并集
- b = t & s # t 和 s的交集
- c = t – s # 求差集(項在t中,但不在s中)
- d = t ^ s # 對稱差集(項在t或s中,但不會同時出現在二者中)
- 基本操作:
- t.add('x') # 添加一項
- s.update([10,37,42]) # 在s中添加多項
- 使用remove()可以删除一項:
- t.remove('H')
- len(s)
- set 的長度
- x in s
- 測試 x 是否是 s 的成員
- x not in s
- 測試 x 是否不是 s 的成員
- s.issubset(t)
- s <= t
- 測試是否 s 中的每一個元素都在 t 中
- s.issuperset(t)
- s >= t
- 測試是否 t 中的每一個元素都在 s 中
- s.union(t)
- s | t
- 傳回一個新的 set 包含 s 和 t 中的每一個元素
- s.intersection(t)
- s & t
- 傳回一個新的 set 包含 s 和 t 中的公共元素
- s.difference(t)
- s - t
- 傳回一個新的 set 包含 s 中有但是 t 中沒有的元素
- s.symmetric_difference(t)
- s ^ t
- 傳回一個新的 set 包含 s 和 t 中不重複的元素
- s.copy()
- 傳回 set “s”的一個淺複制
- 請注意: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。
- 另外,Set 和 ImmutableSet 兩者都支援 set 與 set 之間的比較。兩個 sets 在也隻有在這種情況下是相等的:每一個 set 中的元素都是另一個中的元素(二者互為subset)。一個 set 比另一個 set 小,隻有在第一個 set 是第二個 set 的 subset 時(是一個 subset,但是并不相等)。一個 set 比另一個 set 打,隻有在第一個 set 是第二個 set 的 superset 時(是一個 superset,但是并不相等)。
- 子 set 和相等比較并不産生完整的排序功能。例如:任意兩個 sets 都不相等也不互為子 set,是以以下的運算都會傳回 False:a<b, a==b, 或者a>b。是以,sets 不提供 __cmp__ 方法。
- 因為 sets 隻定義了部分排序功能(subset 關系),list.sort() 方法的輸出對于 sets 的清單沒有定義。
- 運算符
- 運算結果
- hash(s)
- 傳回 s 的 hash 值
- 下面這個表列出了對于 Set 可用二對于 ImmutableSet 不可用的運算:
- 運算符(voperator)
- 等價于
- 運算結果
- s.update(t)
- s |= t
- 傳回增加了 set “t”中元素後的 set “s”
- s.intersection_update(t)
- s &= t
- 傳回隻保留含有 set “t”中元素的 set “s”
- s.difference_update(t)
- s -= t
- 傳回删除了 set “t”中含有的元素後的 set “s”
- s.symmetric_difference_update(t)
- s ^= t
- 傳回含有 set “t”或者 set “s”中有而不是兩者都有的元素的 set “s”
- s.add(x)
- 向 set “s”中增加元素 x
- s.remove(x)
- 從 set “s”中删除元素 x, 如果不存在則引發 KeyError
- s.discard(x)
- 如果在 set “s”中存在元素 x, 則删除
- s.pop()
- 删除并且傳回 set “s”中的一個不确定的元素, 如果為空則引發 KeyError
- s.clear()
- 删除 set “s”中的所有元素
- 請注意:非運算符版本的 update(), intersection_update(), difference_update()和symmetric_difference_update()将會接受任意 iterable 作為參數。從 2.3.1 版本做的更改:以前所有參數都必須是 sets。
- 還請注意:這個子產品還包含一個 union_update() 方法,它是 update() 方法的一個别名。包含這個方法是為了向後相容。程式員們應該多使用 update() 方法,因為這個方法也被内置的 set() 和 frozenset() 類型支援。
【題目:050】| 說說decorator的用法和它的應用場景,如果可以的話,寫一個decorator
[python] view plain copy
- 所謂裝飾器就是把函數包裝一下,為函數添加一些附加功能,裝飾器就是一個函數,參數為被包裝的函數,傳回包裝後的函數:
- def d(fp):
- def _d(*arg, **karg):
- print "do sth before fp.."
- r= fp(*arg, **karg)
- print "do sth after fp.."
- return r
- return _d
- @d
- def f():
- print "call f"
- #上面使用@d來表示裝飾器和下面是一個意思
- #f = d(f)
- f()#調用f
【題目:051】 | 寫一個類,并讓它盡可能多的支援操作符 [python] view plain copy
- class Array:
- __list = []
- def __init__(self):
- print "constructor"
- def __del__(self):
- print "destructor"
- def __str__(self):
- return "this self-defined array class"
- def __getitem__(self, key):
- return self.__list[key]
- def __len__(self):
- return len(self.__list)
- def Add(self, value):
- self.__list.append(value)
- def Remove(self, index):
- del self.__list[index]
- def DisplayItems(self):
- print "show all items----"
- for item in self.__list:
- print item
- arr = Array() #constructor
- print arr #this self-defined array class
- print len(arr) #0
- arr.Add(1)
- arr.Add(2)
- arr.Add(3)
- print len(arr) #3
- print arr[0] #1
- arr.DisplayItems()
- #show all items----
- #1
- #2
- #3
- arr.Remove(1)
- arr.DisplayItems()
- #show all items----
- #1
- #3
- #destructor
【題目:052】| 說一說你見過比較cool的python實作
[python] view plain copy
- cool的概念,角度不同,看法可能也就不同,個人覺得更Pythonic的代碼就是最酷的代碼。
【題目:053】 | Python如何實作單例模式 [python] view plain copy
- #-*- encoding=utf-8 -*-
- print '----------------------方法1--------------------------'
- #方法1,實作__new__方法
- #并在将一個類的執行個體綁定到類變量_instance上,
- #如果cls._instance為None說明該類還沒有執行個體化過,執行個體化該類,并傳回
- #如果cls._instance不為None,直接傳回cls._instance
- class Singleton(object):
- def __new__(cls, *args, **kw):
- if not hasattr(cls, '_instance'):
- orig = super(Singleton, cls)
- cls._instance = orig.__new__(cls, *args, **kw)
- return cls._instance
- class MyClass(Singleton):
- a = 1
- one = MyClass()
- two = MyClass()
- two.a = 3
- print one.a
- #3
- #one和two完全相同,可以用id(), ==, is檢測
- print id(one)
- #29097904
- print id(two)
- #29097904
- print one == two
- #True
- print one is two
- #True
- print '----------------------方法2--------------------------'
- #方法2,共享屬性;所謂單例就是所有引用(執行個體、對象)擁有相同的狀态(屬性)和行為(方法)
- #同一個類的所有執行個體天然擁有相同的行為(方法),
- #隻需要保證同一個類的所有執行個體具有相同的狀态(屬性)即可
- #所有執行個體共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict)
- #可參看:http://code.activestate.com/recipes/66531/
- class Borg(object):
- _state = {}
- def __new__(cls, *args, **kw):
- ob = super(Borg, cls).__new__(cls, *args, **kw)
- ob.__dict__ = cls._state
- return ob
- class MyClass2(Borg):
- a = 1
- one = MyClass2()
- two = MyClass2()
- #one和two是兩個不同的對象,id, ==, is對比結果可看出
- two.a = 3
- print one.a
- #3
- print id(one)
- #28873680
- print id(two)
- #28873712
- print one == two
- #False
- print one is two
- #False
- #但是one和two具有相同的(同一個__dict__屬性),見:
- print id(one.__dict__)
- #30104000
- print id(two.__dict__)
- #30104000
- print '----------------------方法3--------------------------'
- #方法3:本質上是方法1的更新(或者說進階)版
- #使用__metaclass__(元類)的進階python用法
- class Singleton2(type):
- def __init__(cls, name, bases, dict):
- super(Singleton2, cls).__init__(name, bases, dict)
- cls._instance = None
- def __call__(cls, *args, **kw):
- if cls._instance is None:
- cls._instance = super(Singleton2, cls).__call__(*args, **kw)
- return cls._instance
- class MyClass3(object):
- __metaclass__ = Singleton2
- one = MyClass3()
- two = MyClass3()
- two.a = 3
- print one.a
- #3
- print id(one)
- #31495472
- print id(two)
- #31495472
- print one == two
- #True
- print one is two
- #True
- print '----------------------方法4--------------------------'
- #方法4:也是方法1的更新(進階)版本,
- #使用裝飾器(decorator),
- #這是一種更pythonic,更elegant的方法,
- #單例類本身根本不知道自己是單例的,因為他本身(自己的代碼)并不是單例的
- def singleton(cls, *args, **kw):
- instances = {}
- def _singleton():
- if cls not in instances:
- instances[cls] = cls(*args, **kw)
- return instances[cls]
- return _singleton
- @singleton
- class MyClass4(object):
- a = 1
- def __init__(self, x=0):
- self.x = x
- one = MyClass4()
- two = MyClass4()
- two.a = 3
- print one.a
- #3
- print id(one)
- #29660784
- print id(two)
- #29660784
- print one == two
- #True
- print one is two
- #True
- one.x = 1
- print one.x
- #1
- print two.x
- #1
【題目:054】| 如何用Python來發送郵件
[python] view plain copy
- # 可以使用smtplib标準庫。
- # 以下代碼可以在支援SMTP監聽器的伺服器上執行。
- import sys, smtplib
- fromaddr = raw_input("From: ")
- toaddrs = raw_input("To: ").split(',')
- print("Enter message, end with ^D:")
- msg = ''
- while 1:
- line = sys.stdin.readline()
- if not line:
- break
- msg += line
- # 發送郵件部分
- server = smtplib.SMTP('localhost')
- server.sendmail(fromaddr, toaddrs, msg)
- server.quit()
【題目:055】| Python自動連接配接ssh的代碼
[python] view plain copy
- #!/usr/bin/env python
- #import the need library.
- import pxssh
- #machine details
- hostname = ''
- username = ''
- password = ''
- #command we want to send
- command = 'ls -lart'
- #function to connect
- def connect(hostname, username, password, release):
- try:
- s = pxssh.pxssh()
- s.login(hostname, username, password, release)
- print s
- return s
- except Exception, e:
- print "[-] Error Connecting: " + str(e)
- #func to send a command
- def send_command(ssh_session, command):
- ssh_session.sendline(command)
- ssh_session.prompt()
- print ssh_session.before
- #main()
- if __name__ == "__main__":
- session = connect(hostname, username, password)
- send_command(session, command)
或者用pexpect子產品
[python] view plain copy
- #!/usr/bin/env python
- import pexpect
- def ssh_cmd(ip, passwd, cmd):
- ret = -1
- ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
- try:
- i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
- if i == 0 :
- ssh.sendline(passwd)
- elif i == 1:
- ssh.sendline('yes\n')
- ssh.expect('password: ')
- ssh.sendline(passwd)
- ssh.sendline(cmd)
- res = ssh.read()
- print res
- ret = 0
- except pexpect.EOF:
- print "EOF"
- ssh.close()
- ret = -1
- except pexpect.TIMEOUT:
- print "TIMEOUT"
- ssh.close()
- ret = -2
- return ret
- #main()
- if __name__ == "__main__":
- ssh_cmd('127.0.0.1', 'password', 'ls -lart')
【 題目:056】 | 介紹一下Python Date Time方面的類
[python] view plain copy
- 一.time子產品
- time子產品提供各種操作時間的函數
- 一般有兩種表示時間的方式:
- 第一種: 是時間戳的方式(相對于1970.1.1 00:00:00以秒計算的偏移量),時間戳是惟一的
- 第二種: 以數組的形式表示即(struct_time),共有九個元素,分别表示,同一個時間戳的struct_time會因為時區不同而不同
- 二.datetime子產品
- Python提供了多個内置子產品用于操作日期時間,像calendar,time,datetime。time子產品。
- 相比于time子產品,datetime子產品的接口則更直覺、更容易調用。
- datetime子產品定義了下面這幾個類:
- datetime.date:表示日期的類。常用的屬性有year, month, day;
- datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond;
- datetime.datetime:表示日期時間。
- datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。
- datetime.tzinfo:與時區有關的相關資訊。
- datetime中,表示日期時間的是一個datetime對象
- datetime中提供了strftime方法,可以将一個datetime型日期轉換成字元串:
【題目:057】| 寫一個簡單的Python socket程式設計
伺服器端程式:
[python] view plain copy
- # FileName: server.py
- import socket
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.bind(('localhost', 8001))
- sock.listen(5)
- while True:
- conn, addr = sock.accept()
- try:
- conn.settimeout(5)
- buff = conn.recv(1024)
- if buff == '1':
- conn.send('Hello, Client...')
- else:
- conn.send('Please, Go Out...')
- except socket.timeout:
- print 'Socket Time Out...'
- finally:
- conn.close()
用戶端程式:
[python] view plain copy
- # FileName: client.py
- import socket
- import time
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect(('localhost', 8001))
- time.sleep(2)
- sock.send('1')
- print sock.recv(1024)
- 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
- Tooltip控件是一個簡單,但非常有用的控件。它能夠為我們的軟體提供非常漂亮的提示資訊,提高軟體的可用性,給使用者比較好的體驗。
- 假設現在有兩個按鈕,一個用來預覽吊線世系圖,一個用來預覽行轉。為了保持按鈕文本的簡潔,以及為按鈕尺寸所限。
- 我們不能可能把這個按鈕的主要功能通過text屬性表述清楚,這個時候我們就可以用到tooltip控件了.
【題目:059】 | 解釋一下python的and-or文法
[python] view plain copy
- 0 and * 不需要再考慮*是0還是1,結果是0
- 1 and * 需要考慮*是0還是1來決定結果。
- 1 or * 不需要考慮後面的*,結果為1
- 0 or * 需要考慮後面的*來決定結果
- 這個文法看起來類似于 C 語言中的 bool ? a : b 表達式。整個表達式從左到右進行演算,是以先進行 and 表達式的演算。 1 and 'first' 演算值為 'first',然後 'first' or 'second' 的演算值為 'first'。
- 0 and 'first' 演算值為 False,然後 0 or 'second' 演算值為 'second'。
- and-or主要是用來模仿 三目運算符 bool?a:b的,即當表達式bool為真,則取a否則取b。
- and-or 技巧,bool and a or b 表達式,當 a 在布爾上下文中的值為假時,不會像 C 語言表達式 bool ? a : b 那樣工作。
【題目:060】 | Python裡關于“堆”這種資料結構的子產品是哪個?“堆”有什麼優點和缺點
這個真沒有!
【題目:061】| 實作一個stack
[python] view plain copy
- class Stack :
- def __init__( self ):
- ''''' Creates an empty stack. '''
- self._items = list()
- def isEmpty(self):
- ''''' Returns True if the stack is empty or False otherwise. '''
- return len(self) == 0
- def __len__(self):
- ''''' Returns the number of items in the stack. '''
- return len(self._items)
- def peek(self):
- ''''' Returns the top item on the stack without removing it. '''
- assert not self.isEmpty(), "Cannot peek at an empty stack"
- return self._items[-1]
- def pop(self):
- ''''' Removes and returns the top item on the stack. '''
- assert not self.isEmpty(), "Cannot pop from an empty stack"
- return self._items.pop()
- def push(self,item):
- ''''' Push an item onto the top of the stack. '''
- 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
- import re
- src = "security/afafsff/?ip=123.4.56.78&id=45"
- m = re.search('ip=(\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3})', src, re.S) # re.S 改變'.'的行為
- print m.group(1)
- # 輸出結果
- >>>
- 123.4.56.78
【題目:064】| 已知倉庫中有若幹商品,以及相應庫存,類似:
襪子,10
鞋子,20
拖鞋,30
項鍊,40
要求随機傳回一種商品,要求商品被傳回的機率與其庫存成正比。請描述實作的思路或者直接寫一個實作的函數
[python] view plain copy
- # -*- coding: utf-8 -*-
- import random
- Wa_Zhi = ['WZ'] * 100
- Xie_Zi = ['XZ'] * 200
- Tuo_Xie = ['TX'] * 300
- Xiang_Lian = ['XL'] * 400
- All_Before = Wa_Zhi + Xie_Zi + Tuo_Xie + Xiang_Lian
- All_After = random.sample(All_Before, 100)
- print All_After.count('WZ')
- print All_After.count('XZ')
- print All_After.count('TX')
- print All_After.count('XL')
- #輸出結果,大緻滿足需求1: 2: 3: 4的比例
- >>>
- 9
- 19
- 32
- 40