python学习之模块函数

查看模块包含内容

dir

__all__  定义了模块的公有接口,及from modulename import *的函数接口

1 import copy
2 copy.__all__
3 ['Error', 'copy', 'deepcopy']
4 dir(copy)
5 ['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_dispatch', '_copy_immutable', '_copy_inst', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_inst', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', '_test', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

查看模块源码

1 print copy.__file__

 

sys

sys.argv[] 接受脚本运行时输入的参数

 

os

os.environ  对环境变量进行映射

os.system  运行外部程序  

os.system('/usr/bin/firefox')  启动环境浏览器程序

 

fileinput  轻松遍历文件所有行

input(files, [,inplace[, backup]]) 遍历多个输入流中的行,返回可以用于for循环的对象。files为序列文件名对象,inplace=True时,代表原地处理。

 

heapq

heappush(heap, x)  将x推入堆

heappop(heap) 将堆中最小的元素弹出

heapify(heap) 将堆属性强制运用于任意列表

heapreplace(heap, x) 将堆中最小元素弹出,同时将x入堆

1 from heapq import *
2 data = [1, 4, 2, 8, 5, 12, 11, 22, 3]
3 heapify(data)
4 data    ##[1, 3, 2, 4, 5, 12, 11, 22, 8]

 

 

双端队列:在需要按照元素增加的顺序来移除元素时非常有用。

deque

 1 from collections import deque
 2 q = deque(range(5))
 3 q   ##deque([0, 1, 2, 3, 4])
 4 q.append(5)
 5 q.appendleft(6)
 6 q   ##deque([6, 0, 1, 2, 3, 4, 5])
 7 q.pop() ##5
 8 q.popleft() ##6
 9 q  ##deque([0, 1, 2, 3, 4])
10 q.rotate(2)  ##向右位移
11 q ##deque([3, 4, 0, 1, 2])
12 q.rotate(-1)
13 q  ##deque([4, 0, 1, 2, 3])

 

time

1 from time import *
2 asctime()  ##'Fri Jun 01 10:29:10 2012'
3 time()  ##1338517757.375
4 localtime(1338517757.375)
5 time.struct_time(tm_year=2012, tm_mon=6, tm_mday=1, tm_hour=10, tm_min=29, tm_sec=17, tm_wday=4, tm_yday=153, tm_isdst=0)
6 asctime(localtime(1338517757.375)) ##'Fri Jun 01 10:29:17 2012'

 

random  包含返回随机数的函数

random()  返回0<=n<1之间的随机实数n

getrandbits(n)  以长整形式返回n个随机数

uniform(a, b)  返回随机数n, a<=n<b

randrange([start], stop, [step]) 返回range(start, stop, step)中的随机数

choice(seq) 从序列seq中返回随机数

shuffle(seq[, random])  将可变序列seq的元素随机移位

sample(seq, n)  从seq中选取n个随机且独立的元素

 

re

正则:

. 通配符,匹配一个字母

\ 转义

字符集

[a-z]

[^abc]  匹配除abc外字符

| 管道 ‘name|age’二选一

 

 

用ipython运行:

re:

In [713]: import re


In [714]: pattern = re.compile(r"a.*?b")

In [715]: pattern

Out[715]: re.compile(r'a.*?b')





In [716]: result = pattern.match("abdeed")
In [717]: result

Out[717]: <_sre.SRE_Match at 0x10930e510>

In [718]: result.group()

Out[718]: 'ab'





In [721]: result = pattern.search("aaaaaaabccccdd")
In [722]: result

Out[722]: <_sre.SRE_Match at 0x10930e578>

In [723]: result.group()

Out[723]: 'aaaaaaab'







In [729]: re.findall(r"[0-9a-zA-Z]+?", "abcd1")
Out[729]: ['a', 'b', 'c', 'd', '1']

In [730]: re.findall(r"[0-9a-zA-Z]+", "abcd1")

Out[730]: ['abcd1']







In [734]: u = re.sub(r"[a-zA-Z]", "a", "111abcd2222")
In [735]: u

Out[735]: '111aaaa2222'





In [741]: format = "hhl"    ##short, short, long

In [737]: from struct import pack, unpack
In [738]: result = pack(format, 1,2,3)



In [743]: result
Out[743]: '\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

In [744]: unpack(format, result)

Out[744]: (1, 2, 3)







datetime

In [745]: import datetime




In [751]: delta = datetime.timedelta(days=3, seconds=120)
In [752]: delta

Out[752]: datetime.timedelta(3, 120)

In [753]: delta.days

Out[753]: 3

In [754]: delta.seconds

Out[754]: 120

In [755]: delta.microseconds

Out[755]: 0





In [756]: datetime.date.today()

Out[756]: datetime.date(2012, 12, 29)



In [760]: d = datetime.date.today()
In [762]: d.strftime("%Y/%m/%d")

Out[762]: '2012/12/29'





In [763]: datetime.datetime.today()
Out[763]: datetime.datetime(2012, 12, 29, 22, 43, 48, 227647)

In [764]: datetime.datetime.now()

Out[764]: datetime.datetime(2012, 12, 29, 22, 43, 53, 226347)





In [767]: datetime.datetime.strptime("2012:12:18", "%Y:%m:%d")

Out[767]: datetime.datetime(2012, 12, 18, 0, 0)



In [746]: datetime.datetime.now()

Out[746]: datetime.datetime(2012, 12, 29, 22, 35, 24, 322871)









from collections import  (Counter, deque, defaultdict)



In [771]: c = Counter('gallahad')
In [772]: c

Out[772]: Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})

In [773]: c = Counter({'red': 4, 'blue': 2})

In [774]: c

Out[774]: Counter({'red': 4, 'blue': 2})

In [775]: c = Counter(cats=4, dogs=8)

In [776]: c

Out[776]: Counter({'dogs': 8, 'cats': 4})





In [777]: c.elements()
Out[777]: <itertools.chain at 0x109313250>

In [778]: list(c.elements())

Out[778]:

['cats',

 'cats',

 'cats',

 'cats',

 'dogs',

 'dogs',

 'dogs',

 'dogs',

 'dogs',

 'dogs',

 'dogs',

 'dogs']





In [779]: c.most_common()
Out[779]: [('dogs', 8), ('cats', 4)]

In [780]: c.most_common(1)

Out[780]: [('dogs', 8)]





In [781]: c = Counter(a=4, b=2, c=0, d=-2)
In [782]: d = Counter(a=1, b=2, c=3, d=4)

In [783]: c.subtract(d)

In [784]: c

Out[784]: Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})







In [786]: from collections import deque
In [787]: d = deque("abcdef")

In [788]: d

Out[788]: deque(['a', 'b', 'c', 'd', 'e', 'f'])

In [789]: d.

d.append      d.appendleft  d.clear       d.count       d.extend      d.extendleft  d.maxlen      d.pop         d.popleft     d.remove      d.reverse     d.rotate





In [793]: from collections import defaultdict
In [794]: s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

In [795]: d = defaultdict(list)

In [796]: [d[k].append(v) for k, v in s ]

Out[796]: [None, None, None, None, None]



In [801]: d

Out[801]: defaultdict(<type 'list'>, {'blue': [2, 4], 'red': [1], 'yellow': [1, 3]})



In [814]: l = [1, [1, 2], [3, 4]]
In [815]: ml = l

In [816]: cl = copy(l)

In [817]: dcl = deepcopy(l)





In [822]: l.append(5)
In [823]: l

Out[823]: [1, [1, 2], [3, 4], 5]

In [824]: ml

Out[824]: [1, [1, 2], [3, 4], 5]

In [825]: cl

Out[825]: [1, [1, 2], [3, 4]]

In [826]: dcl

Out[826]: [1, [1, 2], [3, 4]]





In [827]: l[1].append(6)
In [828]: l

Out[828]: [1, [1, 2, 6], [3, 4], 5]

In [829]: ml

Out[829]: [1, [1, 2, 6], [3, 4], 5]

In [830]: cl

Out[830]: [1, [1, 2, 6], [3, 4]]

In [831]: dcl

Out[831]: [1, [1, 2], [3, 4]]





from random import (randint, )

In [834]: random.randint(1,3)

Out[834]: 2

In [841]: random.choice([1,2,3])

Out[841]: 2

In [845]: random.sample([1,2,3,4,5], 2)

Out[845]: [2, 4]





In [848]: a = [1,2,3,4,5]
In [852]: random.shuffle(a)

In [853]: a

Out[853]: [1, 5, 2, 4, 3]







import itertools

In [855]: itertools.chain("abc", "eft")
Out[855]: <itertools.chain at 0x109394d10>

In [856]: list(itertools.chain("abc", "eft"))

Out[856]: ['a', 'b', 'c', 'e', 'f', 't']





In [907]: from itertools import combinations
In [908]: combinations("abcdef", 2)

Out[908]: <itertools.combinations at 0x1093a9c00>

In [909]: list(combinations("abcdef", 2))

Out[909]:

[('a', 'b'),

 ('a', 'c'),

 ('a', 'd'),

 ('a', 'e'),

 ('a', 'f'),

 ('b', 'c'),

 ('b', 'd'),

 ('b', 'e'),

 ('b', 'f'),

 ('c', 'd'),

 ('c', 'e'),

 ('c', 'f'),

 ('d', 'e'),

 ('d', 'f'),

 ('e', 'f')]







In [911]: from itertools import compress
In [912]: compress("abcdefg", [1, 0, 1, 0, 1, 0, 1])

Out[912]: <itertools.compress at 0x1093a2610>

In [913]: list(compress("abcdefg", [1, 0, 1, 0, 1, 0, 1]))

Out[913]: ['a', 'c', 'e', 'g']





In [915]: from itertools import count
In [916]: count(2, 0.5)

Out[916]: count(2, 0.5)

In [917]: u = count(2, 0.5)

In [918]: u.next()

Out[918]: 2

In [919]: u.next()

Out[919]: 2.5

In [920]: u.next()

Out[920]: 3.0

In [921]: u.next()

Out[921]: 3.5

In [922]: u.next()

Out[922]: 4.0

In [923]: u.next()

Out[923]: 4.5









In [924]: from itertools import cycle
In [925]: c = cycle("abc")

In [926]: c.next()

Out[926]: 'a'

In [927]: c.next()

Out[927]: 'b'

In [928]: c.next()

Out[928]: 'c'

In [929]: c.next()

Out[929]: 'a'

In [930]: c.next()

Out[930]: 'b'







In [932]: d = dropwhile(lambda x: x < 4, [1, 3, 5, 2, 7, -1, 8])
In [933]: d

Out[933]: <itertools.dropwhile at 0x1093ae998>

In [934]: list(d)

Out[934]: [5, 2, 7, -1, 8]







In [935]: from itertools import group by

In [941]: [(k, list(v)) for k, v in groupby("aaaabbbbb")]

Out[941]: [('a', ['a', 'a', 'a', 'a']), ('b', ['b', 'b', 'b', 'b', 'b'])]

In [943]: [(k, list(v)) for k, v in groupby("abc")]

Out[943]: [('a', ['a']), ('b', ['b']), ('c', ['c'])]



In [944]: u = filter(lambda x:x > 2, [2, 3, 5, -1])
In [945]: u

Out[945]: [3, 5]

In [946]: from itertools import ifilter

In [947]: i = ifilter(lambda x: x > 2, [2, 3, 5, -1])

In [948]: i

Out[948]: <itertools.ifilter at 0x109aa86d0>

In [949]: list(i)

Out[949]: [3, 5]







In [950]: from itertools import imap
In [951]: m = imap(pow, (1, 2), (2, 2))

In [952]: m

Out[952]: <itertools.imap at 0x109aa8690>

In [953]: list(m)

Out[953]: [1, 4]

In [954]: map(pow, (1, 2), (2, 2))

Out[954]: [1, 4]







In [957]: from itertools import islice
In [958]: islice("abcdefg", 0, 4, 2)

Out[958]: <itertools.islice at 0x109a88470>

In [959]: list(islice("abcdefg", 0, 4, 2))

Out[959]: ['a', 'c']







In [962]: from itertools import izip
In [963]: z = izip("abc", "efgh")

In [964]: z

Out[964]: <itertools.izip at 0x109a8a098>

In [965]: list(z)

Out[965]: [('a', 'e'), ('b', 'f'), ('c', 'g')]

In [966]: zip("abc", "efgh")

Out[966]: [('a', 'e'), ('b', 'f'), ('c', 'g')]







In [967]: from itertools import permutations
In [968]: p = permutations("abcd", 3)

In [969]: p

Out[969]: <itertools.permutations at 0x10937fb30>

In [970]: list(p)

Out[970]:

[('a', 'b', 'c'),

 ('a', 'b', 'd'),

 ('a', 'c', 'b'),

 ('a', 'c', 'd'),

 ('a', 'd', 'b'),

 ('a', 'd', 'c'),

 ('b', 'a', 'c'),

 ('b', 'a', 'd'),

 ('b', 'c', 'a'),

 ('b', 'c', 'd'),

 ('b', 'd', 'a'),

 ('b', 'd', 'c'),

 ('c', 'a', 'b'),

 ('c', 'a', 'd'),

 ('c', 'b', 'a'),

 ('c', 'b', 'd'),

 ('c', 'd', 'a'),

 ('c', 'd', 'b'),

 ('d', 'a', 'b'),

 ('d', 'a', 'c'),

 ('d', 'b', 'a'),

 ('d', 'b', 'c'),

 ('d', 'c', 'a'),

 ('d', 'c', 'b')]







In [971]: from itertools import repeat
In [972]: r = repeat("ab", 3)

In [973]: r

Out[973]: repeat('ab', 3)

In [974]: list(r)

Out[974]: ['ab', 'ab', 'ab']







In [975]: from itertools import takewhile
In [976]: t = takewhile(lambda x: x < 4, [1, 2, 2, 5, 6])

In [977]: t

Out[977]: <itertools.takewhile at 0x109a8ad88>

In [978]: list(t)

Out[978]: [1, 2, 2]











sys

In [979]: from sys import argv

In [981]: from sys import exc_info

In [982]: from sys import exit

In [983]: from sys import path





subprocess

In [984]: from subprocess import call

In [985]: from subprocess import Popen





time

In [986]: from time import sleep
In [987]: from time import strftime





In [988]: from time import time
In [989]: time()

Out[989]: 1356836610.631446





os

In [992]: from os import getpid
In [993]: from os import getppid



In [990]: from os import getuid



In [1036]: from os import listdir

In [1037]: listdir(u'/Users/chen/project/temp')
Out[1037]: [u'.git', u'delete_mac.py', u'temp.c', u'temp.py', u'temp.sh', u'test.py']







pickle

In [994]: from pickle import dumps, dump
In [995]: from pickle import loads, load







glob

In [996]: from glob import glob



os.path

In [1009]: pwd

Out[1009]: u'/Users/chen/project/temp/temp.py'



In [1011]: abspath(pwd)

Out[1011]: u'/Users/chen/project/temp/temp.py'



In [1013]: basename(pwd)
Out[1013]: u'temp.py'





In [1016]: dirname(pwd)

Out[1016]: u'/Users/chen/project/temp'



In [1021]: exists(pwd)

Out[1021]: True



In [1024]: isfile(pwd)

Out[1024]: True



In [1027]: isdir(pwd)

Out[1027]: False



 [1031]: join(pwd, "hello.py")
Out[1031]: u'/Users/chen/project/temp/temp.py/hello.py'





In [1033]: split(pwd)
Out[1033]: (u'/Users/chen/project/temp', u'temp.py')









functools

In [1047]: from functools import partial
In [1048]: fun = partial(int, base=2)



In [1051]: fun('11')

Out[1051]: 3





inspect

In [1062]: import inspect
In [1063]: def temp():

   ......:     pass

   ......:

In [1064]: inspect.isfunction(temp)

Out[1064]: True



In [1065]: inspect.ismethod(temp)

Out[1065]: False

 

posted on 2012-04-25 21:10  huhuchen  阅读(326)  评论(0)    收藏  举报

导航