Python built-in functions Review

filter sorted heapq counter namedtuple  reduce deque pickle islice re.split endswith stat os 

#filter

>>> aa = [1,2,3,45,6,7]

>>> list(filter(lambda x:x>3,aa))

>>> [45, 6, 7]

 

#sorted 

>>> sorted(d.items(),key=lambda x:x[1],reverse=True)

 

#heapq

>>> import heapq

>>> heap.nlargest(3,[1,2,2,2,3,4,4,45,5,6])

 

#counter

>>> from collections import Counter

>>> aa = Counter([1,2,2,2,3,4,4,45,5,6])

>>> aa.most_common(3)

 

#namedtuple

>>> from collection import namedtuple

>>> Stu = namedtuple('Stu',['name','age','sex'])

>>> s2 = Stu('jm',16,'male')

>>> s2.name

'Etc.'

 

#reduce

>>> dl = [{'d':3,'a':2,'b':4},{'f':3,'g':2,'b':4},{'d':3,'f':2,'b':4}]

>>> reduce(lambda a,b : a & b ,map(dict.keys,dl))

 

#deque

>>> from collections import deque

>>> q = deque([],5)

>>> q.append(1)

>>> import pickle

>>> pickle.dump(q,open('save.pkl','wb'))

>>> pickle.load(open('save.pkl','rb'))

and ([1], maxlen = 5)

 

#islice

>>> from functools import islice

>>> list(islice(range(10),4,6))

[4, 5]

>>> def query_by_order(d,a,b=None):

...     a -= 1

...     if b is None:

...             b= a+1

...     return list(islice(d,a,b))

 

#re.split

>>> re.split ( '[;, |] +' 'from; ffff | gdhgdjh, jfjje')

[ 'Down', 'ffff', 'gdhgdjh', 'jfjje']

 

#endswith stat os executable permissions

>>> import stat

>>> import os

>>> for fn in os.listdir():

...     if fn.endswith(('.py','.sh')):

...             fs = os.stat (the fn)

...             os.chmod(fn,fs.st_mode | stat.S_IXUSR)

 

# Re.sub replacement string

>>> re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1',log)

Guess you like

Origin www.cnblogs.com/Erick-L/p/11161777.html