python官方文档

python标准库

Python常用小段程序

注:

Cython

Cython项目以开发能把 Python代码转换为等价C代码的编译器为基础。C代码随后在 Cython
环境中执行。这种编译机制使得在 Python代码中嵌亼能够提升效率的C代码成为可能。 Cython可
以被视为一门新的编程语言,它的发明实现了两种编程语言的融合。可以从网上找到大量相关文
档。
建议你访问链接

Jython

跟 Cython相对应的,还有完全用Java语言开发和编译的 Jython。它是由 Jim hugunin在1997年
开发的(http://www.jython.org)。Jython是用Java语言实现的Python编程语言。更进一步来讲,它
具有以下特点: Python的扩展和包是用Java类而不是 Python模块实现的。

PyPy

PyPy解释器是一种即时( Just-in-time,JIT)编译器,它在运行时直接把 Python代码转化为机
器码。这样做是为了提升代码的执行速度,却因此只使用了所有 Python命令中的很少一部分。这
个只包含少数 Python命令的子集被称作 RPython。
关于PyPy的更多信息,请访问其官网http://pypy.org

python基础

1.避免显示for循环,使用函数式编程

  1. items = [1,2,3,4,5]
  2. for item in items:
  3. item + 1
  4. # out:[2,3,4,5,6]

使用map函数

  1. items = [1,2,3,4,5]
  2. def inc(x):return x+1
  3. list(map(inc,items))
  4. # out:[2,3,4,5,6]

使用lambda

  1. items = [1,2,3,4,5]
  2. list(map(lambda x:x+1),items)
  3. # out:[2,3,4,5,6]
  4. # filter()函数只抽取函数返回结果为True的列表元素。
  5. list(filter(lambda x:x<4),items)
  6. # out:[1,2,3]

2.列表生成式

  1. s = [x**2 for x in range(5)]:
  2. s
  3. # out:[0,1,4,9,16]

3.遍历map键值对

  1. for key,value in map:
  2. print(key,value)

4.判断一个变量是否是某个类型

当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?reference
type() 判断对象类型
isinstance() 判断class的类型
dir() 获得一个对象的所有属性和方法
配合getattr()setattr()以及hasattr(),我们可以直接操作一个对象的状态:

  1. >>>isinstance(a, list)
  2. True
  3. >>> isinstance(b, Animal)
  4. True
  5. >>> isinstance(c, Dog)
  6. True
  7. >>> type(123)
  8. <class 'int'>
  9. >>> type('str')
  10. <class 'str'>
  11. >>> type(None)
  12. <type(None) 'NoneType'>
  13. >>> type(123)==type(456)
  14. True
  15. >>> type(123)==int
  16. True
  17. >>> type('abc')==type('123')
  18. True
  19. >>> type('abc')==str
  20. True
  21. >>> type('abc')==type(123)
  22. False

dir() 获得一个对象的所有属性和方法
配合getattr()setattr()以及hasattr(),我们可以直接操作一个对象的状态:

  1. >>>isinstance(a, list)
  2. True
  3. >>> isinstance(b, Animal)
  4. True
  5. >>> isinstance(c, Dog)
  6. True
  7. >>> type(123)
  8. <class 'int'>
  9. >>> type('str')
  10. <class 'str'>
  11. >>> type(None)
  12. <type(None) 'NoneType'>
  13. >>> type(123)==type(456)
  14. True
  15. >>> type(123)==int
  16. True
  17. >>> type('abc')==type('123')
  18. True
  19. >>> type('abc')==str
  20. True
  21. >>> type('abc')==type(123)
  22. False

5.enumerate

enumerate is useful for obtaining an indexed list:

  1. nums = [2,3,4]
  2. for i,e in enumerate(nums,1):
  3. print(i,e)
  4. print('--------------')
  5. for i,e in enumerate(nums,2):
  6. print(i,e)
  7. 输出:
  8. 1 2
  9. 2 3
  10. 3 4
  11. ------------
  12. 2 2
  13. 3 3
  14. 4 4

6.作图美化

  1. %config InlineBackend.figure_format = 'retina'
  2. %matplotlib inline
  3. import seaborn as sns
  4. sns.set(font= "Kaiti",style="ticks",font_scale=1.4)
  5. import matplotlib
  6. import matplotlib.pyplot as plt
  7. matplotlib.rcParams['axes.unicode_minus']=False # 解决坐标轴的负号显示问题

7.python函数参数带**

参考
解释
查阅资料后发现,参数前面加上 号 ,意味着参数的个数不止一个,另外带一个星号()参数的函数传入的参数存储为一个元组(tuple),带两个()号则是表示字典(dict)。
一个(
)号还可以解压参数列表。
还可以同时使用一个()和(*

  1. def t4(a, b=10, *args, **kwargs):
  2. print(a)
  3. print(b)
  4. print(args)
  5. print(kwargs)
  6. t4(1, 2, 3, 4, e=5, f=6, g=7)
  7. # 1
  8. # 2
  9. # 3 4
  10. # {'e': 5, 'g': 7, 'f': 6}

8.python并行(1)

Parallel,delayed用法 参考

9.import logging (python日志)

  • 日志常用指引
  • 日志操作手册 | 级别 | 何时使用 | | —- | —- | | DEBUG | 细节信息,仅当诊断问题时适用。 | | INFO | 确认程序按预期运行。 | | WARNING | 表明有已经或即将发生的意外(例如:磁盘空间不足)。程序仍按预期进行。 | | ERROR | 由于严重的问题,程序的某些功能已经不能正常执行 | | CRITICAL | 严重的错误,表明程序已不能继续执行 |

默认的级别是 WARNING,意味着只会追踪该级别及以上的事件,除非更改日志配置。
所追踪事件可以以不同形式处理。最简单的方式是输出到控制台。另一种常用的方式是写入磁盘文件。

  1. def finalUse():
  2. logging.basicConfig(filename='example.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
  3. str = 'string'
  4. num = 10
  5. logging.debug('This message should go to the log file')
  6. logging.info('So should this')
  7. logging.warning('And this, too')
  8. logging.info('vary as string "%s" and number "%d" can be also used in.', str, num)
  9. logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
  1. import logging
  2. def demo01():
  3. # 简单例子
  4. logging.warning('Watch out!') # will print a message to the console
  5. logging.info('I told you so') # will not print anything
  6. str = '变量'
  7. num = 10
  8. logging.warning('print %s %d', str, num)
  9. def demo02():
  10. logging.basicConfig(filename='example.log', level=logging.DEBUG)
  11. logging.debug('This message should go to the log file')
  12. logging.info('So should this')
  13. logging.warning('And this, too')
  14. logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
  15. def demo03():
  16. # 更改显示消息的格式
  17. logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) # 没有 root
  18. logging.debug('This message should appear on the console')
  19. logging.info('So should this')
  20. logging.warning('And this, too')
  21. def demo04():
  22. # 在消息中显示日期/时间
  23. logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m-%d-%Y %I:%M:%S %p')
  24. # logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
  25. logging.warning('is when this event was logged.')
  26. def finalUse():
  27. logging.basicConfig(filename='example.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
  28. str = 'string'
  29. num = 10
  30. logging.debug('This message should go to the log file')
  31. logging.info('So should this')
  32. logging.warning('And this, too')
  33. logging.info('vary as string "%s" and number "%d" can be also used in.', str, num)
  34. logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
  35. if __name__ == '__main__':
  36. # demo04()
  37. finalUse()

10.迭代器 iter

官方文档参考

  1. class MySentences(object):
  2. def __init__(self, dirname):
  3. self.dirname = dirname
  4. def __iter__(self):
  5. for fname in os.listdir(self.dirname):
  6. for line in open(os.path.join(self.dirname, fname)):
  7. yield line.split()
  8. sentences = MySentences('/some/directory') # a memory-friendly iterator
  9. model = gensim.models.Word2Vec(sentences)

Numpy

1. array()

  1. a = np.array([1,2,3])
  2. # a = np.array([1,2,3],dtype = float16) # 指定数据类型
  3. # a = np.array([1,2,3],dtype = int16)
  4. # a = np.array([1,2,3],dtype = float64)
  5. # a = np.array([1,2,3],dtype = complex) # 复数
  6. b = np.array([1,2,3],[4,5,6])
  7. a
  1. a.ndim
  2. # out:1
  3. a.size
  4. # out:3
  5. a.shape
  6. # out:(3L,)
  7. a.itemsize
  8. # out: (a =)3 (b =)6

检测新创建的对象是否是 ndarray很简单,只需要把新声明的变量传递给type()函数即可

type(a)

调用变量的 dtype属性,即可获知新建的 ndarray属于哪种数据类型。
a.dtype
dtype( ‘ int32 ‘ )
我们刚建的这个数组只有一个轴,因而秩的数量为1,它的型为(3,1)。这些值的获取方法如
下:轴数量需要使用ndim属性,数组长度使用size属性,而数组的型要用 shape属性。
a.ndim
a.size
a.shape

ndarray对象拥有另外一个叫作 itemsize的重要属性。它定义了数组中每个元素的长度为几个
字节。

b.itemsze

2.np.ones()、np.zeros()、np.arange()

  1. >>>npzeros((3, 3))
  2. array([[0.,0.,0.],
  3. [0.,0.,0.],
  4. [0.,0.,0.]])
  5. >>np.ones((3,3))
  6. array([[1.,1.,1.],
  7. [1.,1.,1.],
  8. [1.,1.,1.]])
  1. >>>np arange(4, 10)
  2. array([4,5,6,7,8,9])
  3. >>>np arange(o, 12, 3) # 加入步长
  4. array([0,3,6,9])
  5. # arange 与 Python的 range()函数有所不同了, range()函数只可以使用整数作为步长
  6. >>>np arange(o,6,0.6 # 步长可以是float、double
  7. array([0.,0.6,1.2,1.8,2.4,3.,3.6,4,2,4.8,5.4])
  8. >>>np arange(0, 12).reshape (3,4)
  9. array([0,1,2,3],
  10. [4,5,6,7],
  11. [8,9,10,11])

3.np.random.random()

  1. np.random.random(3,3)
  2. np.random.randomn(3,3) # 数据符合正态分布

4.矩阵积 dot(),矩阵乘法*

  1. np.dot(A,B)
  2. A.dot(B)
  3. A*B 不等于 B*A

5.索引、切片

索引简单理解,不记

切片

  1. a[:,0]
  2. a[:,1:]
  3. a[:,-1]

6.结构化数组

  1. bytes b1
  2. int i1,i2,i4,i8
  3. unsigned ints u1,u2,u4,u8
  4. floats f2,f4,f8
  5. complex C8,C16
  6. fixed length strings a<n>
  1. >>>structured= np.array([(1,'First, 0.5, 1+2j),(2,'Second, 1.3, 2-2j),
  2. (3,'Third',o.8,1+3j)], dtype=('i2,a6,f4,c8'))
  3. >>> structured