《Python基础教程》读书笔记10-模块,标准库

模块

使用 dir

dir 函数可以将对象的所有属性(以及模块的所有函数、类、变量等)列出。

>>> import copy
>>> dir(copy)
['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_copy_dispatch', '_copy_immutable', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

>>> [n  for n in dir(copy) if not n.startswith('_')]
['Error', 'PyStringMap', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

all变量

>>> copy.__all__
['Error', 'copy', 'deepcopy']

如果使用 from copy import *,那么就只能使用 __all__ 变量中的函数。如果要使用其他函数,则需要 from copy import XXX

用 help 获取帮助

用 help 含函数与查看函数文档字符串相比,可以获得更多信息,比如所带参数。

>>> help(copy.copy)
Help on function copy in module copy:

copy(x)
    Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

>>> print(copy.copy.__doc__)
Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

查看源代码

>>> print (copy.__file__)
C:\python3.5\lib\copy.py

标准库

sys

  1. 变量sys.argv包含传递到Python解释器的参数,包括脚本名称。
  2. 函数sys.exit可以退出当前程序,大多数使用默认参数0,表示成功,也可以使用字符串用作错误信息。
  3. 映射sys.modules将模块名映射到实际存在的模块上,只应用于目前导入的模块。
  4. 变量sys.path一个字符串列表,解释器将从这些目录中查找模块。
  5. 变量sys.platform一个字符串,平台的名称,如:操作系统名字(win32),运行Jython就是java虚拟机(java1.6.12).
  6. 变量sys.stdin,sys.stdout,sys.stderr,类文件流对象,标准输入、标准输出和标准错误。

写一个脚本 test.py

import sys
args = sys.argv[1:] # 第一个参数是脚本的名字
args.reverse()
print(' '.join(args))

在 Shell 中运行,或 MS-DOS 中运行

$ python test.py this is a test
test a is this

fileinput

遍历文本文件的所有行。

  1. fileinput.input([files[, inplace[, backup]]]),返回能够用于for循环遍历的对象。
    (1)files,序列或字符串,提供一个或多个文件名。
    (2)inplace,布尔值,是否进行原地处理,对于要访问的每一行,需要打印出替代的内容,以返回到当前的输入文件中。容易破坏文件,应该在不使用这个参数时,仔细测试程序,确保正确后再修改文件。
    (3)backup,当inplace为True时,backup参数将文件名扩展备份到通过原始文件创建的备份文件中。
  2. fileinput.filename()函数返回当前正在处理的文件名。
  3. fileinput.lineon()函数返回当前行数。如果处理多个文件,这个值是累计的,处理下一个文件时,行数不会重置。
  4. fileinput.isfirstline()函数判断当前行是否是当前文件的第一行,是返回True,否返回False。
  5. fileinput.isstdin()函数在当前文件为sys.stdin时返回真值,否则假值。
  6. fileinput.nextfile()函数会关闭当前文件,跳到下一个文件,跳过的行并不计。
  7. fileinput.close()函数关闭整个文件链。结束迭代。
# numberlines.py
# 为文本文件添加行号

import fileinput

for line in fileinput.input(inplace=True):
    line = line.rstrip()
    num = fileinput.lineno()
    print ('%-40s # %2i' % (line, num))

运行程序

$ python numberlines.py numberlines.py

位于i位置上的元素总比i/2位置上的元素大(反之来说就是i位置上的元素总比2*i以及2*i+1位置上的元素小)。

Python中没有堆类型,有一个包含一些堆操作函数的模块,这个模块叫做heapqqqueue的缩写,即队列)

heappush函数

heappush 函数用于增加堆的项。只能用于通过各种堆函数建立的列表中,不能是之前的普通列表。

>>> from heapq import *
>>> from random import shuffle
>>> data = range(10)
>>> shuffle(data) # Python2.7不会报错,Python 3.5会报错,range() 返回的是“range object”,而不是实际的list 值
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    shuffle(data)
  File "C:\python3.5.2\lib\random.py", line 272, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'range' object does not support item assignment
>>> data = list(range(10))
>>> shuffle(data)
>>> data
[2, 5, 8, 0, 6, 3, 1, 7, 4, 9]
>>> heap = []
>>> for n in data:
    heappush(heap, n)

>>> heappush(heap, 0.5)
>>> heap
[0, 0.5, 1, 4, 2, 8, 3, 7, 5, 9, 6]

heappop 函数

heappop 函数弹出最小的元素,一般就是索引0处的元素。

>>> heappop(heap)
0
>>> heappop(heap)
0.5
>>> heappop(heap)
1
>>> heap
[2, 4, 3, 5, 9, 8, 6, 7]

heapify 函数

heapify 函数使用任意列表作为参数,并将其转换为合法的堆。

>>> heap = [3, 5, 6, 8, 4, 2, 7, 1, 9]
>>> heapify(heap)
>>> heap
[1, 3, 2, 5, 4, 6, 7, 8, 9]

heapreplace 函数

heapreplace 函数弹出堆的最小元素,并将新元素推入。这样比 heappop 之后再调用 heappush 更高效。

>>> heap
[1, 3, 2, 5, 4, 6, 7, 8, 9]
>>> heapreplace(heap, 0.5)
1
>>> heapreplace(heap, 10)
0.5
>>> heap
[2, 3, 6, 5, 4, 10, 7, 8, 9]

nlargest(n, iter)

返回 iter 中第 n 大的元素。

nsmllest(n, iter)

返回 iter 中第 n 小的元素。

双端队列

双端队列(double-ended queue,或称deque),collections 模块。

>>> from collections import deque
>>> q = deque(range(5))
>>> q
deque([0, 1, 2, 3, 4])
>>> q.append(5)
>>> q.appendleft(6)
>>> q
deque([6, 0, 1, 2, 3, 4, 5])
>>> q.pop()
5
>>> q.popleft()
6
>>> q.rotate(3) # 元素左移3个,或者说指针,指向第一个元素的指针
>>> q
deque([2, 3, 4, 0, 1])
>>> q.rotate(-1) # 元素右移1个
>>> q
deque([3, 4, 0, 1, 2])

shelve

在文件中存储数据,进行普通字典(键是字符串)来操作。

>>> import shelve
>>> s = shelve.open(r'C:\Users\bin\Desktop\python\test\shelve.dat') # Python3.5,2.7,目录中有这个shelve.dat文件,且文件不是shelve创建的,就会报错,
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    s = shelve.open(r'C:\Users\bin\Desktop\python\test\shelve.dat')
  File "C:\python3.5.2\lib\shelve.py", line 243, in open
    return DbfilenameShelf(filename, flag, protocol, writeback)
  File "C:\python3.5.2\lib\shelve.py", line 227, in __init__
    Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File "C:\python3.5.2\lib\dbm\__init__.py", line 88, in open
    raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
>>> s = shelve.open(r'C:\Users\bin\Desktop\python\test\shelve.dat') # 如果源文件不存在 Python3.5 会生成shelve.dat.dat文件,文件大小0kb。
# 如果源文件不存在 Python2.7 会生成shelve.dat文件,文件大小24kb
>>> s['x'] = ['a', 'b', 'c'] # Python3.5 生成shelve.dat.dir文件
>>> s['x'].append('d')
>>> s['x'] # 刚新增的'd',不存在
['a', 'b', 'c']
>>> temp = s['x'] # 可以这么做,保存在临时变量中,再新增'd',最后重新存储这个副本
>>> temp.append('d')
>>> s['x'] = temp
>>> s['x']
['a', 'b', 'c', 'd']
>>> s.close() # 记得关闭 Python3.5 生成shelve.dat.bak文件
# 也可以将open函数的writeback参数设置为True,这样所有读取或赋值操作都会保存在内存中,在close后保存到磁盘中。数据小可以这么做。
>>> s = shelve.open(r'C:\Users\bin\Desktop\python\test\shelve.dat',writeback=True)
>>> s['x'].append('e')
>>> s['x']
['a', 'b', 'c', 'd', 'e']
>>> s.close()

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:《Python基础教程》读书笔记10-模块,标准库

文章字数:2.1k

本文作者:Bin

发布时间:2017-01-01, 22:41:44

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2017/01/01/Python%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/%E3%80%8APython%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B%E3%80%8B%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B010-%E6%A8%A1%E5%9D%97%EF%BC%8C%E6%A0%87%E5%87%86%E5%BA%93/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录