python面试总结(二)列表去重与单例
生活随笔
收集整理的這篇文章主要介紹了
python面试总结(二)列表去重与单例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?1.Python里面如何實(shí)現(xiàn)tuple和list的轉(zhuǎn)換python中,tuple和list均為內(nèi)置類型,
? ? ? ? tuple([1,2,3]) #list轉(zhuǎn)換為tuple
? ? ? ? 以tuple作為參數(shù)將list類初始化,將返回list類型
? ? ? ? ist((1,2,3)) #tuple轉(zhuǎn)換為list
? ? ? ? 1.函數(shù)tuple(seq)可以把所有可迭代的(iterable)序列轉(zhuǎn)換成一個tuple, 元素不變,排序也不變。
? ? ? ? 例如,tuple([1,2,3])返回(1,2,3), tuple(‘a(chǎn)bc’)返回(‘a(chǎn)’.'b’,'c’).如果參數(shù)已經(jīng)是一個tuple的話,函數(shù)不做任何拷貝而直接返回原來的對象,所以在不確定對象是不是tuple的時候來調(diào)用tuple()函數(shù)也不是很耗費(fèi)的。
? ? ? ? 2.函數(shù)list(seq)可以把所有的序列和可迭代的對象轉(zhuǎn)換成一個list,元素不變,排序也不變。
? ? ? ? 例如 list([1,2,3])返回(1,2,3), list(‘a(chǎn)bc’)返回['a', 'b', 'c']。如果參數(shù)是一個list, 她會像set[:]一樣做一個拷貝
2.Python里面re模塊match()和search()的區(qū)別?
? ? ?match()函數(shù)只檢測RE是不是在string的開始位置匹配
? ? search()會掃描整個string查找匹配,會掃描整個字符串并返回第一個成功的匹配
? ? 也就是說match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none
? ? 二、例子:
? ? match():
? ? print(re.match(‘super’, ‘superstition’).span())會返回(0, 5)
? ? print(re.match(‘super’, ‘insuperable’))則返回None search():
? ? print(re.search(‘super’, ‘superstition’).span())返回(0, 5)
? ? print(re.search(‘super’, ‘insuperable’).span())返回(2, 7)
3.下面代碼會輸出什么:
li = [1, 1, 2, 3, 3, 4, 4, 5, 5, 6] a = [] # 列表去重方法一:集合方法 b = set(li) print(b)# 列表去重方法二:遍歷統(tǒng)計次數(shù),刪除重復(fù)選項 for i in li:while li.count(i) > 1:del li[li.index(i)] print(li)# 列表去重方法三:遍歷列表,添加新列表對比 a = [] for i in li:if i in li:if i not in a:a.append(i) print(a)#列表去重方法四:先對元素進(jìn)行排序,然后從列表的最后開始掃描 list = [1, 1, 2, 3, 3, 4, 4, 5, 5, 6] if list:list.sort()last = list[-1]for i in range(len(list)-2,-1,-1):if last == list[i]:del list[i]else:last = list[i]print(list)#列表去重方法五:利用map的fromkeys來自動過濾重復(fù)值 l1 = [1, 1, 2, 3, 3, 4, 4, 5, 5, 6] l2 = {}.fromkeys(l1).keys() print(l2)
5.請簡述python中單例模式的特點(diǎn),并手寫一個單例模式?
# 所謂單例,是指一個類的實(shí)例從始至終只能被創(chuàng)建一次。# 方法1: # 如果想使得某個類從始至終最多只有一個實(shí)例,使用__new__方法會很簡單。Python中類是通過__new__來創(chuàng)建實(shí)例的:class Singleton(object):_instance = Nonedef __new__(cls, *args, **kw):if not cls._instance:cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)return cls._instanceclass MyClass(Singleton):a = 1 one=MyClass() two=MyClass() print(id(one),id(two))# 結(jié)果:id相同 # 在上面的代碼中,我們將類的實(shí)例和一個類變量 _instance 關(guān)聯(lián)起來, # 如果 cls._instance 為 None 則創(chuàng)建實(shí)例,否則直接返回 cls._instance。# 方法2: # 有時候我們并不關(guān)心生成的實(shí)例是否具有同一id,而只關(guān)心其狀態(tài)和行為方式。 # 我們可以允許許多個實(shí)例被創(chuàng)建,但所有的實(shí)例都共享狀態(tài)和行為方式:class Borg(object): _shared_state={} def __new__(cls,*args,**kwargs): obj=super(Borg,cls).__new__(cls,*args,**kwargs) obj.__dict__=cls._shared_state return obj # 將所有實(shí)例的__dict__指向同一個字典,這樣實(shí)例就共享相同的方法和屬性。 # 對任何實(shí)例的名字屬性的設(shè)置,無論是在__init__中修改還是直接修改,所有的實(shí)例都會受到影響。 # 不過實(shí)例的id是不同的。要保證類實(shí)例能共享屬性,但不和子類共享,注意使用cls._shared_state, # 而不是Borg._shared_state。 # 因為實(shí)例是不同的id,所以每個實(shí)例都可以做字典的key:if __name__=='__main__': class Example(Borg): pass a=Example() b=Example() c=Example() adict={} j=0 for i in a,b,c: adict[i]=j j+=1 for i in a,b,c: print(adict[i] ) # 結(jié)果: # 0 # 1 # 2 # 如果這種行為不是你想要的,可以為Borg類添加__eq__和__hash__方法, # 使其更接近于單例模式的行為:class Borg(object): _shared_state={} def __new__(cls,*args,**kwargs): obj=super(Borg,cls).__new__(cls,*args,**kwargs) obj.__dict__=cls._shared_state return obj def __hash__(self): return 1 def __eq__(self,other): try: return self.__dict__ is other.__dict__ except: return False if __name__=='__main__': class Example(Borg): pass a=Example() b=Example() c=Example() adict={} j=0 for i in a,b,c: adict[i]=j j+=1 for i in a,b,c: print(adict[i]) # 結(jié)果: # 2 # 2 # 2 # 所有的實(shí)例都能當(dāng)一個key使用了。# 方法3 # 當(dāng)你編寫一個類的時候,某種機(jī)制會使用類名字,基類元組,類字典來創(chuàng)建一個類對象。新型類中這種機(jī)制默認(rèn)為type,而且這種機(jī)制是可編程的,稱為元類__metaclass__ 。class Singleton(type): def __init__(self,name,bases,class_dict): super(Singleton,self).__init__(name,bases,class_dict) self._instance=None def __call__(self,*args,**kwargs): if self._instance is None: self._instance=super(Singleton,self).__call__(*args,**kwargs) return self._instance if __name__=='__main__': class A(object): __metaclass__=Singleton a=A() b=A() print (id(a),id(b)) # 結(jié)果: # 34248016 34248016 # id是相同的。 # 例子中我們構(gòu)造了一個Singleton元類,并使用__call__方法使其能夠模擬函數(shù)的行為。 # 構(gòu)造類A時,將其元類設(shè)為Singleton,那么創(chuàng)建類對象A時,行為發(fā)生如下: # A=Singleton(name,bases,class_dict),A其實(shí)為Singleton類的一個實(shí)例。 # 創(chuàng)建A的實(shí)例時,A()=Singleton(name,bases,class_dict)()=Singleton(name,bases,class_dict).__call__(),這樣就將A的所有實(shí)例都指向了A的屬性_instance上,這種方法與方法1其實(shí)是相同的。# 方法4 # python中的模塊module在程序中只被加載一次,本身就是單例的。可以直接寫一個模塊,將你需要的方法和屬性,寫在模塊中當(dāng)做函數(shù)和模塊作用域的全局變量即可,根本不需要寫類。 # 而且還有一些綜合模塊和類的優(yōu)點(diǎn)的方法:class _singleton(object): class ConstError(TypeError): pass def __setattr__(self,name,value): if name in self.__dict__: raise self.ConstError self.__dict__[name]=value def __delattr__(self,name): if name in self.__dict__: raise self.ConstError raise NameError import sys sys.modules[__name__]=_singleton() # python并不會對sys.modules進(jìn)行檢查以確保他們是模塊對象, # 我們利用這一點(diǎn)將模塊綁定向一個類對象,而且以后都會綁定向同一個對象了。 # 將代碼存放在single.py中:import single single.a=1single.a=2 ConstError>>> del single.a ConstError# 方法5: # 最簡單的方法:class singleton(object): pass singleton=singleton() # 將名字singleton綁定到實(shí)例上,singleton就是它自己類的唯一對象了。
總結(jié)
以上是生活随笔為你收集整理的python面试总结(二)列表去重与单例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 语言4位bcd码怎么加加_S730040
- 下一篇: websocket python爬虫_p