Python改变列表中数据类型的方法
- 方法1:
a=['123','345','147']
b=[]
for i in a:
j = float(i)
b.append(j)
- 方法2:
a=['123','345','147']
b=a[:2]
b=numpy.array(b,dtype='float_')#把列表的数据类型全部都变为浮点型
....
- 方法3:
a=['123','345','147']
b=[int(i) for i in a]
....
Python3中新函数(gt,ge,eq,le,lt)替代Python2中cmp()函数
import operator #首先要导入运算符模块
operator.gt(1,2) #意思是greater than(大于)
operator.ge(1,2) #意思是greater and equal(大于等于)
operator.eq(1,2) #意思是equal(等于)
operator.le(1,2) #意思是less and equal(小于等于)
operator.lt(1,2) #意思是less than(小于)
#lt(a, b) 相当于 a < b
#le(a,b) 相当于 a <= b
#eq(a,b) 相当于 a == b
#ne(a,b) 相当于 a != b
#gt(a,b) 相当于 a > b
#ge(a, b)相当于 a>= b
#函数的返回值是数值,不是布尔值。
Numpy中repeat函数使用
repeat是属于ndarray对象的方法:
- numpy.repeat(a,repeats,axis=None)
- object(ndarray).repeat(repeats,axis=None)
参数的意义:
- axis=None,会flatten当前矩阵,实际上就是变成了一个行向量
- axis=0,沿着y轴复制,实际上增加了行数
- axis=1,沿着x轴复制,实际上增加列数
- repeats可以为一个数,也可以为一个矩阵
import numpy as np
a=np.array(([1,2],[3,4]))
print(a)
[[1 2]
[3 4]]
print(np.repeat(a,2))
[1 1 2 2 3 3 4 4]
print(np.repeat(a,2,axis=1))
[[1 1 2 2]
[3 3 4 4]]
print(np.repeat(a,2,axis=0))
[[1 2]
[1 2]
[3 4]
[3 4]]
print(np.repeat(a,[2,3],axis=0))
#复制第一行元素repeats[0]次,复制第二行元素repeats[1]次,依次类推.
#若repeat矩阵length(repeats)!=length(a[:,:1])将会报错。
[[1 2]
[1 2]
[3 4]
[3 4]
[3 4]]