作者: 張昆_Python 鏈接: https://blog.csdn.net/u013205877/article/details/77542837
1.如何反向迭代一個(gè)序列 #如果是一個(gè)list,最快的方法使用reverse tempList = [1,2,3,4] tempList.reverse() for x in tempList: print x
#如果不是list,需要手動(dòng)重排 templist = (1,2,3,4) for i in range(len(templist)-1,-1,-1): print templist[i]
2.如何查詢和替換一個(gè)文本中的字符串#最簡(jiǎn)單的方法使用replace() tempstr = 'hello you hello python are you ok' print tempstr.replace('you','python')
#還可以使用正則,有個(gè)sub() tempstr = 'hello you hello python are you ok' import re rex = r'(hello|Use)' print re.sub(rex,'Bye',tempstr)
3.使用python實(shí)現(xiàn)單例模式#方法一:可以使用__new__方法 #在__new__方法中把類實(shí)例綁定到類變量_instance上,,如果cls._instance為None表示該類還沒(méi)有實(shí)例化過(guò),,實(shí)例化該類并返回,。如果cls_instance不為None表示該類已實(shí)例化,直接返回cls_instance class SingleTon(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,'_instance'): cls._instance = object.__new__(cls,*args,**kwargs) return cls._instance class TestClass(SingleTon): a = 1
test1 = TestClass() test2 = TestClass() print test1.a,test2.a
test1.a=2 print test1.a,test2.a
print id(test1),id(test2)
#方法二:使用裝飾器,建立過(guò)實(shí)例的就放到instances里面,下次建立的時(shí)候先檢查里面有沒(méi)有 def SingleTon(cls,*args,**kwargs): instances = {} print instances def _singleton(): if cls not in instances: instances[cls] = cls(*args,**kwargs) print instances return instances[cls] return _singleton
@SingleTon class LastClass(object): a = 1 test1 = LastClass() print test1.a test2 = LastClass() print test2.a
#方法三:使用__metaclass__(元類)關(guān)于元類看看這個(gè)吧;http://blog./21351/ class SignalTon(type): def __init__(cls,name,bases,dict): super(SignalTon, cls).__init__(name,bases,dict) cls._instance = None
def __call__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(SignalTon,cls).__call__(*args,**kwargs) return cls._instance
class TestClass(object): __metaclass__ = SignalTon
test1 = TestClass() test2 = TestClass()
test1.a = 2 print test1.a,test2.a print id(test1),id(test2)
#方法四:共享屬性 所謂單例就是所有的引用(實(shí)例,,對(duì)象)擁有相同的屬性和方法,,同一個(gè)類的實(shí)例天生都會(huì)有相同的方法,那我們只需要保證同一個(gè)類所產(chǎn)生的實(shí)例都具有相同的屬性,。所有實(shí)例共享屬性最簡(jiǎn)單直接的方法就是共享__dict__屬性指向,。
class SingleTon(object): _state = {} def __new__(cls, *args, **kwargs): obj = object.__new__(cls,*args,**kwargs) obj.__dict__ = cls._state return obj
class TestClass(SingleTon): a = 1
test1 = TestClass() test2 = TestClass() print test1.a,test2.a test1.a = 2 print test1.a,test2.a print id(test1),id(test2) #方法五:使用同一個(gè)模版 #寫在mysingleton.py中 class My_Singleton(object): def foo(self): pass
my_singleton = My_Singleton()
#寫在要使用這個(gè)實(shí)例的py文件里面,在不同的引用的地方都引用相同的實(shí)例,以此實(shí)現(xiàn)單例模式 from mysingleton import my_singleton my_singleton.foo()
4.重新實(shí)現(xiàn)str.strip()def rightStrip(tempStr,splitStr): endindex = tempStr.rfind(splitStr) while endindex != -1 and endindex == len(tempStr) - 1: tempStr = tempStr[:endindex] endindex = tempStr.rfind(splitStr) return tempStr
def leftStrip(tempStr,splitStr): startindex = tempStr.find(splitStr) while startindex == 0: tempStr = tempStr[startindex+1:] startindex = tempStr.find(splitStr) return tempStr
str = ' H ' print str print leftStrip(str,' ') print rightStrip(str,' ') #輸出 H H H
5.super的原理#閱讀下面的代碼,它的輸出結(jié)果是什么,? class A(object): def __init__(self): print 'enter A' super(A, self).__init__() # new print 'leave A'
class B(object): def __init__(self): print 'enter B' super(B, self).__init__() # new print 'leave B'
class C(A): def __init__(self): print 'enter C' super(C, self).__init__() print 'leave C'
class D(A): def __init__(self): print 'enter D' super(D, self).__init__() print 'leave D' class E(B, C): def __init__(self): print 'enter E' super(E, self).__init__() # change print 'leave E'
class F(E, D): def __init__(self): print 'enter F' super(F, self).__init__() # change print 'leave F'
#輸出
enter F enter E enter B enter C enter D enter A leave A leave D leave C leave B leave E leave F
非常棒的講解: http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html
6.閉包常用的裝飾器就是閉包的一種
def make_adder(addend): def adder(addend): return addend+addend return adder
P1 = make_adder(5) P2= make_adder(4)
print p1(10) #輸出15 print p2(10) #輸出14
閉包(Closure)是詞法閉包(Lexical Closure)的簡(jiǎn)稱,,是引用了自由變量的函數(shù),。這個(gè)被引用的自由變量將和這個(gè)函數(shù)一同存在,即使已經(jīng)離開了創(chuàng)造它的環(huán)境也不例外 http://www.cnblogs.com/ma6174/archive/2013/04/15/3022548.html https:///python-closure.html 7.給列表中的字典排序list 對(duì)象 alist [{“name”:”a”,”age”:20},{“name”:”b”,”age”:30},{“name”:”c”,”age”:25}]按照 age 從大到小排序 alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}] alist.sort(key=lambda:x:-x.get('age')) print alist
8.合并兩個(gè)列表排除重復(fù)元素用簡(jiǎn)潔的方法合并alist = [‘a(chǎn)’,’b’,’c’,’d’,’e’,’f’] blist = [‘x’,’y’,’z’,’e’,’f’]并且元素不能重復(fù) alist = ['a','b','c','d','e','f'] blist = ['x','y','z','e','f'] def merge_list(*args): s = set() for i in args: s = s.union(i) print(s) return s
merge_list(alist,blist)
9.打亂一個(gè)排好序的列表from random import shuffle alist = range(10) print(alist) shuffle(alist) print(alist)
10.簡(jiǎn)單的實(shí)現(xiàn)一個(gè)棧結(jié)構(gòu) stackclass Stack(object): def __init__(self): self.value = []
def push(self,x): self.value.append(x)
def pop(self): self.value.pop()
stack = Stack()
stack.push(1) stack.push(2) stack.push(3) print(stack.value) stack.pop() print(stack.value)
11.輸入一個(gè)日期,返回時(shí)一年中的哪一天from datetime import datetime def which_day(year,month,day): return (datetime(year,month,day)-datetime(year,1,1)).days+1
print(which_day(2017,1,15))
12.把字符串”k1:1|k2:2|k3:3”處理成 python 字典的形式:{k1:1,k2:2,k3:3}def string_to_dict(string): d = {} for kv in string.split('|'): k,v = kv.split(':') if v.isdigit(): v=int(v) d[k]=v return d
print(string_to_dict('k1:1|k2:2|k3:3'))
13.判斷輸入的值是否在矩陣之中(楊氏矩陣)在一個(gè)二維數(shù)組之中,每一行都按照從走到右遞增的順序排序,每一列到按照從上到下的順序排序.請(qǐng)完成一個(gè)函數(shù),輸入這樣的一個(gè)二維手術(shù)和一個(gè)整數(shù),判斷數(shù)組中是否含有該整數(shù) #處理數(shù)組矩陣 arr = [[1,4,7,10,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]] def get_num(num,data=None): while data: if num > data[0][-1]: del data[0] elif num<>0][-1]: data = list(zip(*data)) del data[-1] data = list(zip(*data)) else: return True data.clear() return False print (get_num(18,arr))
不處理數(shù)組矩陣 使用 step-wise 線性搜索 def getvalue(data,value): m = len(data)-1 n = len(data[0])-1 r = 0 c = n while c>=0 and r<> if value == data[r][c]: return True elif value>data[r][c]: r = r+1 else: c = c-1 return False
14.獲取最大公約數(shù)(歐幾里得算法)a= 25 b=15
def max_common(a,b): while b: a,b=b,a%b return a
詳解: https://blog.csdn.net/franktan2010/article/details/38229641 15.求兩個(gè)數(shù)的最小公倍數(shù)(公式法)兩個(gè)數(shù)的乘積等于這兩個(gè)數(shù)的 最大公約數(shù)與最小公倍數(shù)的積 a=25 b=15 def min_common(a,b): c= a*b while b: a,b=b,a%b return c//a
詳情: https://zhidao.baidu.com/question/90232880 16.獲取中位數(shù) 如果總數(shù)個(gè)數(shù)是奇數(shù),,按從小到大的順序,,取中間的那個(gè)數(shù);如果總數(shù)個(gè)數(shù)是偶數(shù)個(gè)的話,,按從小到大的順序,,取中間那兩個(gè)數(shù)的平均數(shù)。 #計(jì)算中位數(shù) def mediannum(num): listnum = [num[i] for i in range(len(num))] listnum.sort() lnum = len(num) if lnum % 2 == 1: i = int((lnum + 1) / 2)-1 return listnum[i] else: i = int(lnum / 2)-1 return (listnum[i] + listnum[i + 1]) / 2
詳情: https://blog.csdn.net/qq_33363973/article/details/78773144 def medin(data): data.sort() half = len(data)//2 return (data[half]+data[~half])/2 l = [1,3,4,53,2,46,8,42,82] print (median(l))
(完)
看完本文有收獲,?請(qǐng)轉(zhuǎn)發(fā)分享給更多人 關(guān)注「Python那些事」,,做全棧開發(fā)工程師
|