>>> os.environ["HOME"]
'C:\\Users\\Administrator'>>> os.getcwd() #获得当前的目录
'D:\\new'
>>> os.getenv("QTDIR")  #获取环境变量的值
'D:\\vs2010-qt-src-4.7.4\\qt-src-4.7.4'
os.putenv(varname, value)  #设置环境变量的值os.mkdir(path[, mode])
>>> os.mkdir("aa")
>>> os.rmdir("aa")
>>>os.makedirs("aa\\bb\\cc") 多级目录
os.removedirs(path)¶
os.remove("d:\\new\\hello.txt")  #删除文件,如果是目录的话,出错
os.rename("test.txt","a.txt")  random.randint(a, b)
Return a random integer N such that a <= N <= b.
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
random.random()
Return the next random floating point number in the range [0.0, 1.0).
random.shuffle(x[, random])  随机排序序列
random.uniform(a, b)¶返回a<=N<=b之间的浮点数
random.randrange([start], stop[, step])想当于choice(range(start, stop, step))
>>> random.random()        # Random float x, 0.0 <= x < 1.0
0.37444887175646646
>>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
1.1800146073117523
>>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
7
>>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
26
>>> random.choice('abcdefghij')  # Choose a random element
'c'>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]>>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
[4, 1, 5]>>> datetime.MAXYEAR
9999
>>> datetime.MINYEAR
1>>> a=datetime.date(2011,2,1)
>>> a.today()
datetime.date(2011, 11, 26)
>>> a.year
2011
>>> a.month
2
>>> a.day
1>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)  #计算日期之差
>>> time_to_birthday.days
202>>> datetime.now()   #当前时间
datetime.datetime(2011, 11, 26, 10, 40, 10, 283000)
>>> datetime.utcnow()
datetime.datetime(2011, 11, 26, 2, 40, 34, 809000)
>>> a=date(2005,7,14)  #日期和时间进行合并
>>> t=time(12,30,12)
>>> datetime.combine(a,t)
datetime.datetime(2005, 7, 14, 12, 30, 12)
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)>>> from datetime import timedelta, datetime, tzinfo
>>> class GMT1(tzinfo):
...     def __init__(self):         # DST starts last Sunday in March
...         d = datetime(dt.year, 4, 1)   # ends last Sunday in October
...         self.dston = d - timedelta(days=d.weekday() + 1)
...         d = datetime(dt.year, 11, 1)
...         self.dstoff = d - timedelta(days=d.weekday() + 1)
...     def utcoffset(self, dt):
...         return timedelta(hours=1) + self.dst(dt)
...     def dst(self, dt):
...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
...             return timedelta(hours=1)
...         else:
...             return timedelta(0)
...     def tzname(self,dt):
...          return "GMT +1"
...
>>> class GMT2(tzinfo):
...     def __init__(self):
...         d = datetime(dt.year, 4, 1)
...         self.dston = d - timedelta(days=d.weekday() + 1)
...         d = datetime(dt.year, 11, 1)
...         self.dstoff = d - timedelta(days=d.weekday() + 1)
...     def utcoffset(self, dt):
...         return timedelta(hours=1) + self.dst(dt)
...     def dst(self, dt):
...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
...             return timedelta(hours=2)
...         else:
...             return timedelta(0)
...     def tzname(self,dt):
...         return "GMT +2"
...
>>> gmt1 = GMT1()
>>> # Daylight Saving Time
>>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
>>> dt1.dst()
datetime.timedelta(0)
>>> dt1.utcoffset()
datetime.timedelta(0, 3600)
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
>>> dt2.dst()
datetime.timedelta(0, 3600)
>>> dt2.utcoffset()
datetime.timedelta(0, 7200)
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(GMT2())
>>> dt3     # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2     # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
Trueclass datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
>>> a=time(10,46,12)
>>> a.min
datetime.time(0, 0)
>>> a.max
datetime.time(23, 59, 59, 999999)
>>> a.hour
10
>>> a.minute
46
>>> a.second
12
>>> a.microsecond
0class collections.Counter([iterable-or-mapping])
A Counter is a dict subclass for counting hashable objects.
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall('\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']most_common([n])  #出现次数最多的n个
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sum(c.values())  # total of all counts
4
>>> list(c)
['a', 'c', 'b', 'd']
>>> set(c)
set(['a', 'c', 'b', 'd'])
>>> dict(c)
{'a': 4, 'c': 0, 'b': 2, 'd': -2}
>>> c.items()
[('a', 4), ('c', 0), ('b', 2), ('d', -2)]
>>> c.most_common()[:-2:-1]    # c.most_common()[:-n:-1] n least #common elements[('d', -2)]
>>> c+=Counter()
>>> c
Counter({'a': 4, 'b': 2})
>>> c.clear()
>>> c
Counter()>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print elem.upper()
G
H
I>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):File "<pyshell#6>", line 1, in -toplevel-d.pop()
IndexError: pop from an empty deque>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])def tail(filename, n=10):'Return the last n lines of a file'return deque(open(filename), n)def moving_average(iterable, n=3):# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0# http://en.wikipedia.org/wiki/Moving_averageit = iter(iterable)d = deque(itertools.islice(it, n-1))d.appendleft(0)s = sum(d)for elem in it:s += elem - d.popleft()d.append(elem)yield s / float(n)def delete_nth(d, n):d.rotate(-n)d.popleft()d.rotate(n)class collections.defaultdict([default_factory[, ...]])
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> d.items()
[('blue', set([2, 4])), ('red', set([1, 3]))]>>> def heapsort(iterable):
...     'Equivalent to sorted(iterable)'
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')#coding=utf-8
#堆的实例from heapq import heappush, heappop, heappushpop, heapify, heapreplace, nlargest,\nsmallestheap=[]heappush(heap,"A");
heappush(heap,"C");
heappush(heap,"B");print heapheappop(heap)   #弹出堆中最小的元素
print heapvar=heappushpop(heap,"D")  #返回并弹出堆中最小的元素,并且将D压入堆
print var
print heapvar=heapreplace(heap,"E")  #返回并弹出堆中最小的元素,并且将D压入堆,
print var
print heaplist=[1,2,3,4,5,6,7,8,9,0]
heapify(list);
print listprint nlargest(3,list)   #返回堆中最大的3个
print nsmallest(3,list)  #返回堆中最小的3个

  

python标准库学习4相关推荐

  1. python标准库学习笔记

    原创:python标准库学习笔记 数据结构 bisect 模块里实现了一个向列表插入元素时也会顺便排序的算法. struct - 二进制数据结构:用途:在 Python 基本数据类型和二进制数据之间进 ...

  2. Python标准库学习——sys模块

    sys模块可以控制Python Shell窗口信息. 1.version 和 version_info 属性,可以列出目前所使用Python的版本信息. 列出目前所使用Python的版本信息. imp ...

  3. 【Python 标准库学习】容器数据类型库 — collections

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ collections 模块实现了特定目标的容器,以提供Python标准内建容器 ...

  4. 【Python 标准库学习】时间相关的函数库 — time

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ time 模块提供了各种时间相关的函数,该模块中的大多数函数是调用了所在平台 C ...

  5. python标准库学习9

    fileinput 模块允许你循环一个或多个文本文件的内容 使用 fileinput 模块循环一个文本文件 import fileinput import sysfor line in fileinp ...

  6. 【Python 标准库学习】安全哈希与摘要算法库 — hashlib

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ hashlib 模块针对不同的安全哈希和消息摘要算法实现了一个通用的接口.提供了常 ...

  7. 【Python 标准库学习】数据科学计算库 — math

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ math 模块官方文档:https://docs.python.org/3/lib ...

  8. python threading_【python标准库学习】thread,threading(一)多线程的介绍和使用

    在单个程序中我们经常用多线程来处理不同的工作,尤其是有的工作需要等,那么我们会新建一个线程去等然后执行某些操作,当做完事后线程退出被回收.当一个程序运行时,就会有一个进程被系统所创建,同时也会有一个线 ...

  9. 【Python 标准库学习】系统相关的参数和函数库 — sys

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ sys 模块提供了与 Python 解释器紧密相关的一些变量和函数,这些变量可能被 ...

  10. 【Python 标准库学习】多种操作系统接口和常用路径操作库 — os 与 os.path

    欢迎加入 Python 官方文档翻译团队:https://www.transifex.com/python-doc/ os 模块简介:主流操作系统有 Windows.UNIX.Mac OS 等,os ...

最新文章

  1. Android之View绘制流程源码分析
  2. 深度分享:世界顶级计算语言学科学家Ken Church CCL 2018主旨报告(附PPT全文)
  3. 一线城市中高端人才月薪超 2 万,电子通信行业应届生薪资涨幅最高
  4. 粤港澳大湾区菜篮子-哲商对话·林裕豪:从玉农业谋定标准
  5. 4.5. Rspamd
  6. MCU VR班會(05)記錄
  7. 高锟诺奖演讲:《古沙递捷音》
  8. mysql show
  9. java基础—Objcet中的equals方法重写
  10. SxSW小组成员讨论了Valley调查中的Elephant
  11. 有人说智能制造装备前景大好,那么智能制造装备产业园的潜力如何?
  12. java requirenonnull_Java null判断新方法:Objects.requireNonNull 你过用吗?
  13. Python办公自动化【Word】
  14. vnc远程控制软件下载,有哪些实用的vnc远程控制软件下载
  15. mac 锤子android助手,Mac+Android好帮手 锤子SmartFinder
  16. 勃林格殷格翰2022年营收强势增长10.5%,达241亿欧元
  17. 简单电子产品的蓝牙电路设计和PCB设计
  18. 3个python库的图像增强
  19. IDEA查看maven依赖关系的方法
  20. VUE构建工具-姜威-专题视频课程

热门文章

  1. C#精髓【月儿原创】第一讲 使用垃圾回收器
  2. Gridview][UpdateCommand的写法要点]
  3. 20种看asp源码的方法及工具
  4. HTML4.0标准语法--表格
  5. Linux监控工具dstat
  6. C++中函数指针的使用
  7. 写注册机犯法吗_逼着一个受害者去向另一个受害者道歉,不过分吗?
  8. 计算机为什么找不到c盘d盘,电脑不显示是什么盘?是C盘还是D盘?怎么才能显示出来呢?...
  9. linux平台调试终端,10款Linux平台上优秀的调试器,总有一款适合你!
  10. Java项目:课程资源管理+在线考试平台(java+SSH+mysql+maven+tomcat)