Python学习笔记

20221031:对比python的列表数组与numpy插件在数据处理效率上的差别,import time导入了常用的模板,import numpy as np导入numpy模块,别名为np。当时在操作时,pycharm没有安装numpy这个模块,在软件内的terminal模式下使用"pip install numpy"安装好了,有几个新的知识点:

1.科学记数法的表示,1e6表示10的6次方

2.时间戳,time.time()取回与1970年1月1日标准之间的一个时间戳值,某两个时间戳值可以相减运算得到间隔,乘以1000得到毫秒数。

3.四舍五入函数,round(number,digits),两个常用参数,一个是数值,第二个是保留的小数位

import time
import numpy as np
python_array = list(range(int(1e6)))
time_start = time.time()
python_array = [val*5 for val in python_array]
time_end = time.time()
print('time_of_python_array:{}'.format(round(1000*(time_end-time_start),2))+'ms')

numpy_array = np.arange(1e6)
start_time = time.time()
numpy_array = numpy_array*5
end_time = time.time()
print('time_of_numpy_array:{}'.format(round(1000*(end_time-start_time),2))+'ms')

20221101:字典的操作最好用函数进行,setdefault()、pop()、update()、get()来进行,避免程序报错。

 1 #建立一个通讯录字典,键值是姓名,值为号码
 2 phone_number_dict = {
 3     'Andy Lau':'135****5525',
 4     'Jack Chen': '180****6871',
 5     'Bruce Lee': '181****0098',
 6 }
 7 #用一个函数,格式化输出一个完整的字典
 8 def print_phone_number(dic):
 9     if isinstance(dic,dict):#isinstance()用于判断数据类型
10         print('{:<5}{:^20}{:^20}'.format("SN",'NAME','PHONE_NUMBER'))
11         count = 0
12         for k,v in phone_number_dict.items():
13             count= count+1
14             print('{:<5}{:^20}{:^20}'.format(count,k,v))
15     else:
16         print('dic不是一个字典类型的数据。')
17 print_phone_number(phone_number_dict)
18 #增加一个字典元素
19 phone_number_dict['Jim Green']='139****1234'#直接用键引用赋值,如果键存在,则覆盖
20 print(phone_number_dict.setdefault('Jim Green',13000000000))#如果key存在,就返回对应的值
21 print(phone_number_dict.setdefault('Have a try',13000000000))#如果key不存在,就将键值对插入到字典中
22 print_phone_number(phone_number_dict)
23 #删除一个item
24 print(phone_number_dict.pop('have','没有这个键对应的值'))#如果key不存在,则返回第二个参数的值
25 print(phone_number_dict.pop('Have a try','Done'))#如果key存在,则删除该元素,并返回删除的值
26 #修改字典元素的值
27 phone_number_dict.update({'Tom Cruse': '135****0000','Nico King': '182****1234'})#update的参数就是一个字典
28 phone_number_dict.update([('Bison Talay','177****1111'),('Ryu Yamazaki','137****0000')])#也可以是成对的元组列表
29 #当update的键值对已经在原字典中存在有相同的key,则该key所对应的值会被更改
30 print_phone_number(phone_number_dict)
31 #查询字典元素使用get()函数,如果查不到则会返回指定值,不会报错
32 print(phone_number_dict.get('Ryu Yamazaki','查无此人'))#返回主键Ryu Yamazaki对应的值
33 print(phone_number_dict.get('Ryu Samuri','查无此人'))#因为查找不到主键Ryu Samuri,则会返回后面的提示'查无此人'

 对输入字符串内容的检查,可用于纯数字型密码的检测

 1 info = input('>>>')#输入一个字符串
 2 print(info)#打印刚刚输入的字符串
 3 for unit in info:#逐个检查字符串里的字符,如果是字母则替换成空格
 4     if unit.isalpha():
 5         info = info.replace(unit, ' ')
 6 print(info)
 7 info_new = info.split()#将替换后的字符串分开,分隔符默认为空格
 8 print(info_new, len(info_new))#输出分隔后的列表,输出列表元素的个数
 9 num_str = ''#定义一个空字符串
10 for unit in info_new:#把列表中的每个元素拼接成一个新的字符串
11     num_str = num_str + unit
12 print(num_str)#输出新的字符串,此时串中已经全部是数字了
13 print(int(num_str)*5)#将纯数字的字符串转换成整形数值,并扩大五倍后输出

 

to be continue......  

posted @ 2022-11-01 08:42  欠我一个忆  阅读(38)  评论(0)    收藏  举报