""Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values)import doctest doctest.testmod() # 自动验证嵌入测试
unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:
import unittestclass TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70)unittest.main() # Calling from the command line invokes all tests










zhangxv
zha***v95@163.com
参考地址
关于urlopen的补充
#处理get请求,不传data,则为get请求import urllibfrom urllib.request import urlopenfrom urllib.parse import urlencode url='http://www.xxx.com/login'data={"username":"admin","password":123456}req_data=urlencode(data)#将字典类型的请求数据转变为url编码res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的url res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为strprint(res)#处理post请求,如果传了data,则为post请求import urllibfrom urllib.request import Requestfrom urllib.parse import urlencode url='http://www.xxx.com/login'data={"username":"admin","password":123456}data=urlencode(data)#将字典类型的请求数据转变为url编码data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用with urlopen(req_data) as res: res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为strprint(res)zhangxv
zha***v95@163.com
参考地址
redhands
zho***cc@qq.com
参考地址
时间和日期补充
常用时间处理方法
今天
today = datetime.date.today()昨天
yesterday = today - datetime.timedelta(days=1)上个月
last_month = today.month - 1 if today.month - 1 else 12当前时间戳
time_stamp = time.time()时间戳转datetime
datetime.datetime.fromtimestamp(time_stamp)datetime转时间戳
int(time.mktime(today.timetuple()))datetime转字符串
today_str = today.strftime("%Y-%m-%d")字符串转datetime
today = datetime.datetime.strptime(today_str, "%Y-%m-%d")补时差
today + datetime.timedelta(hours=