python的常用数据类型及其使用 python内置数据类型 python numpy模块

刚刚结束python编程,直接看别人的程序,发现python的数据类型都不清楚,特写此笔记帮助理解。Justin Johnson写的python-numpy教程比较简洁,本文基本参考了该教程。

详细手册可参考:https://docs.python.org/3/library/stdtypes.html

基础数据

基础数据类型包括:整数、浮点数、布尔型、字符串型、复数型。(不赘述)

容器类型

内置的containers类型包括:列表lists、字典dictionaries、集合sets和元组tuples。

lists

python中没有内置的array,因此list等价于array,但是list是可变大小、能容纳不同类型元素的一种数据类型。

  1. 创建:方括号。
    xs = [2,1,3]
    nums = list(range(5)) #nums:[0,1,2,3,4]
nums = [0,1,2,3,4]
squares = [x**2 for x in nums] #nums:[0,1,4,9,16]
  1. 随机访问元素:通过下标可访问。
    xs[2]='foo'
  2. 切片Slicing
    nums[2:4]
  3. 遍历元素:
animals = ['a','b','c']
for idx, animal in enumerate(animals):
        print('#%d:%s' %(idx+1, animal))

dictionaries

  1. 创建:花括号。
    d = {'cat':'cute', 'dog':'furry}
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
  1. 随机访问元素:通过键值访问。
    d['cat'] #cute
    d.get('fish', 'N/A') #没有该键值,返回N/A
  2. 遍历元素
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
        legs = d[animal]
        print('A %s has %d legs' % (animal, legs))
for animal, legs in d.items():
        print('A %s has %d legs' % (animal, legs))

sets

sets是不重复元素的无序集。

  1. 创建:花括号。
    animals = {'cat', 'dog'}
nums = {int(sqrt(x)) for x in range(30)} # Prints "{0, 1, 2, 3, 4, 5}"
  1. 遍历元素
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
        print('#%d: %s' % (idx + 1, animal)) #由于是无序的,此处的idx没有意义。

tuples

元组是不可变有序集。类似于list,但区别是tuples可以作为字典的键值,可以作为sets的元素,但lists不行。string/list/tuple/range都是序列。

  1. 创建
t = (5, 6)

python numpy模块

NumPy是Python的一个包,主要由多维的数组对象和一系列封装好的对数组对象进行处理的程序组成。使用NumPy可进行三方面的运算:

  • 对数组进行数字和逻辑运算;
  • 傅里叶转换和维度变换;
  • 与线性代数相关的运算。
    Numpy + Scipy + Matplotlib组合通常可用于替代matlab,经常一起使用。
    Numpy支持的基础数据类型要多于python:bool_/int_/intc/intp/int8/int16/int32/int64/uint8/uint16/uint32/uint64/float_/float16/float32/float64/complex_/complex64/complex128
    Numpy中最重要的对象就是N维数组——ndarray。一个numpy数组是一组类型相同、由非负整数元祖索引的值。
  1. 创建
    a = np.array([1,2,3])
    a = np.zeros((2,2))
    a = np.ones((1,2))
    a = np.full((2,2),7)
    a = np.eye(2)
    a = np.random.random(2,2)

  2. 随机访问元素:整数索引。

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
a[0,1]  # Prints "2"
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
  1. 切片
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:3]
# 0 - 1 rows, columns 1 - 2
# [[2 3]
#  [6 7]]

注意:
- 使用整数索引和切片都可以访问数组元素,但将索引和切片混合的方式得到的数组可能会出现rank降低的情况,但只使用切片则总是得到与原数组相同rank的结果。
- 使用索引的方式总是构造一个新的数组,而使用切片则是原数组的子数组,改变后原数组也会跟着改变。

  1. 广播Broadcasting
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print(y)  # Prints "[[ 2  2  4]
          #          [ 5  5  7]
          #          [ 8  8 10]
          #          [11 11 13]]"