#列表
ldata=range(-2,2) #構造列表
a=filter(lambda x :x >0,ldata) #filter函式
b=[x for x in ldata if x > 0] #列表解析
#字典from random import randint
ddata= #構造字典
c= #字典解析
#集合sdata=set(range(-2,2)) #構造集合
d= #集合解析
#傳統方式訪問
student=('zhangsan',18,'male')
student[0] #name
student[1] #age
student[2] #***
#定義數值常量,類似其他語言列舉型別
name,age,***=range(3)
student=('zhangsan',18,'male')
student[name] #name
student[age] #age
student[***] #***
#使用標準庫中collections.namedtuple替代內建tuple
from collections import namedtuple
student=namedtuple('student',['name','age','***'])
s=student('zhangsan',18,'male') #預設賦值,且s仍然是內建tuple型別
s1=student(name='zhangsan',age=18,***='male') #關鍵字賦值
s.name #name
s.age #age
s.*** #***
from random import randint
from collections import counter
data=[randint(0,20) for _ in range(30)] #建立隨機序列,30個值在0-20的元素
c=counter(data) #構造counter物件,得到統計頻度字典
c1=c.most_common(3) #獲取頻度最高的3個元素項
print(c1)
from random import randint
# 利用zip將字典轉為元組
d= t=zip(d.values(),d.keys())
sorted(t) #優先比較value,value相同則比較key
#利用sorted函式的key引數
sorted(d.items(),key=lambda x :x[1])
有序字典是指字典鍵值對按照插入順序儲存。網上查詢,據說python3.6以前內建的字典是無序的,3.6開始預設有序字典。為確保有序,還是使用有序字典。from random import randint,sample
from functools import reduce
c1=c2=
c3=reduce(lambda a,b:a & b,map(dict.keys,[c1,c2,c3]))
from collections import ordereddict
d=ordereddict()
d['a']=1
d['b']=2
d['c']=3
for x in zip(d):
print(x)
from collections import deque
import pickle
q=deque(,5) #建立乙個容量為5的佇列
for i in range(6):
print(q)
pickle.dump(q,open('history','wb')) #將佇列序列化儲存
q2=pickle.load(open('history','rb')) #將佇列反序列化載入
print(q2)
from itertools import islice
f=open('a.txt','r')
a=f.readlines()[300,500] #需要一次性讀取整個檔案,占用記憶體大
b=islice(f,300,500) #取f的300到500行
# islice(f,300) #取f的前300行
# islice(f,300,none) #取f的300行之後
f.close()
from itertools import chain
x=['a','b','c']
y=['1','2','3','4']
#並行迭代
for a,b in zip(x,y):
print(a,b)
#序列迭代
for a in chain(x,y):
print(a)
a='123;456,xyz|hh python'
b=a.split() #['123;456,xyz|hh', 'python']
import re
c=re.split(r'[;,|\s]+',a) #['123', '456', 'xyz', 'hh', 'python']
import re
a='today is 2018-06-20.'
b=re.sub(r'(\d)-(\d)-(\d)',r'\2/\3/\1',a) #today is 06/20/2018.
c=re.sub(r'(?p\d)-(?p\d)-(?p\d)',r'\g/\g/\g',a) #today is 06/20/2018.
s='abc'
s.ljust(10) #abc
s.ljust(10,'-') #abc-------
s.rjust(10) # abc
s.rjust(10,'=') #*****==abc
s.center(10) # abc
s.center(10,'*') #***abc****
format(s,'<10') #abc
''.format(s) #abc-------
format(s,'>10') # abc
format(s,'^10') # abc
Python高效程式設計技巧
關鍵字 python 高效 程式設計 開源 原文 我已經使用python程式設計有多年了,即使今天我仍然驚奇於這種語言所能讓 表現出的整潔和對dry程式設計原則的適用。這些年來的經歷讓我學到了很多的小技巧和知識,大多數是通過閱讀很流行的開源軟體,如django,flask,requests中獲得的。...
Python高效程式設計技巧
我已經使用python程式設計有多年了,即使今天我仍然驚奇於這種語言所能讓 表現出的整潔和對dry程式設計原則的適用。這些年來的經歷讓我學到了很多的小技巧和知識,大多數是通過閱讀很流行的開源軟體,如django,flask,requests中獲得的。下面我挑選出的這幾個技巧常常會被人們忽略,但它們在...
Python高效程式設計技巧
關鍵字 python 高效 程式設計 開源 原文 我已經使用python程式設計有多年了,即使今天我仍然驚奇於這種語言所能讓 表現出的整潔和對dry程式設計原則的適用。這些年來的經歷讓我學到了很多的小技巧和知識,大多數是通過閱讀很流行的開源軟體,如django,flask,requests中獲得的。...