Python
Python notes
202004
- python中没有null, 有None, python中None的含义和其他语言中null是一样的.
- type(), 查看一个python对象的数据类型
- __init__.py
20200419, Python中函数可以重复实现, 以后出现的为准
def f1():
print(1)
def f1():
print(3)
f1()
# 2
20200419, 一行代码打印九九乘法表
print('\n'.join([' '.join(['%s*%s=%-2s'%(y,x,x*y) for y in range(1,x+1)])for x in range(1,10)]))
print('\n'.join([' '.join('%sx%s=%-2s'%(x,y,x*y) for x in range(1,y+1))for y in range(1,10)]))
- output
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
20200419, Numpy数据类型转换astype,dtype_Python_Aurora Silent-CSDN博客
import numpy as np
arr = np.array([1,2,3,4,5])
# arr: array([1, 2, 3, 4, 5])
# 查看数据类型
# arr.dtype: dtype('int64')
# 转换数据类型
float_arr = arr.astype(np.float64)
# float_arr.dtype: dtype('float64')
# 如果将浮点数转换为整数,则小数部分会被截断
arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])
# arr2.dtype: dtype('float64')
arr2.astype(np.int32) # array([1, 2, 3, 4, 5], dtype=int32)
# 字符串数组转换为数值型
numeric_strings = np.array(['1.2','2.3','3.2141'], dtype=np.string_)
# array(['1.2', '2.3', '3.2141'], dtype='|S6')
# 此处写的是float 而不是np.float64, Numpy很聪明,会将python类型映射到等价的dtype上
numeric_strings.astype(float) # array([1.2 , 2.3 , 3.2141])
20200216, 字符串中插入变量
str = 'ss'
for index_i in range(3):
print('a_%s,%d'%(str,index_i))
# a_ss,0
# a_ss,1
# a_ss,2
20200215, 2.15 字符串中插入变量 — python3-cookbook 3.0.0 文档
# 字符串的 format() 方法
s = '{name} has {n} messages.'
s.format(name='Guido', n=37)
# 'Guido has 37 messages.'
# 如果要被替换的变量能在变量域中找到, 可以结合使用 format_map() 和 vars()
name = 'Guido'
n = 37
s.format_map(vars())
# 'Guido has 37 messages.'
# vars() 也适用于对象实例
class Info:
def __init__(self, name, n):
self.name = name
self.n = n
a = Info('Guido',37)
s.format_map(vars(a))
# 'Guido has 37 messages.'
end
EOF