1.  内置函数
1)常用的内置函数
print(all([0, 2, 3, 4]))  # False,判断可迭代的对象里面的值是否都为真
print(any([0, 1, 2, 3, 4])) # True 判断可迭代的对象里面的值是否有一个为真
print(bin(100), type(bin(100))) # 0b1100100 <class 'str'> 十进制转二进制,二进制前有0b,如果想去掉,用如下方法:
ejz = bin(100)
print(ejz.replace('0b', ''), type(ejz.replace('0b', ''))) # 1100100 <class 'str'>
print(bool('s')) # 把一个对象转换成布尔类型
print(bytearray('abcde', encoding='utf-8')) # 把字符串变成一个可修改的bytes,什么情况下会用到呢???
'''
print(callable('aa'))
# 1. 判断传入的对象是否可被调用,可被调用是指能否使用()(括号)的方法调用
# 2. 可调用对象,在实际调用也可能调用失败;但是不可调用对象,调用肯定不成功。
# 3. 类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了__call__方法。
# >>> callable(1)
# False
# >>> 1()
# Traceback (most recent call last):
# File "<pyshell#5>", line 1, in <module>
# 1()
# TypeError: 'int' object is not callable
# >>> class A: # 定义类A
# pass
#
# >>> callable(A) # 类A是可调用对象
# True
# >>> a = A() # 调用类A
# >>> callable(a) # 实例a不可调用
# False
# >>> a() # 调用实例a失败
# Traceback(most recent call last): File "<pyshell#31>", line 1, in < module > a()
# TypeError: 'A'
# object is not callable
#
# >>> class B: # 定义类B
# def __call__(self):
# print('instances are callable now.')
# >>> callable(B) # 类B是可调用对象
# True
# >>> b = B() # 调用类B
# >>> callable(b) # 实例b是可调用对象
# True
# >>> b() # 调用实例b成功
# instances are callable now.
''' print(chr(65)) # A 打印数字对应的ascii
print(ord('A')) # 65 打印字符对应的ascii码
print(dict(a=1, b=2)) # {'a': 1, 'b': 2} 转换字典
print(dir(1)) # 打印传入对象的可调用方法 ,一般只看不带__的方法,或属性 # print(eval('[]')) # 执行python代码,只能执行简单的运算
# code = '1+1'
# print(eval(code))
# print(exec('def a():pass')) # 执行python代码 code = '''
def a():
print('aa')
a()'''
print(exec(code)) # 结果中有None是因为exec(code)没有返回值,所以输出None
# 结果是
# aa
# None
'''
# zip() # 把可迭代对象(如list)结合在一起,以短的list为准
ids = [1, 2, 3, 4]
names = ['小黑', '小白', '小黄']
# for idd, name in ids, names: # 这种写法会报错
for idd, name in zip(ids, names):
print(idd, name)
结果:
1 小黑
2 小白
3 小黄 print(map(lambda x: x > 5, [1, 2, 3, 4, 5, 6]))
# map:循环调用函数,处理结果保存在map对象中,可以用list(map对象)查看返回结果
# 使用map高级些
# 同样的功能,代码越少越牛逼
def func(a):
if a % 2 == 0:
return a
# return True
else:
return False
# return True [0, True, 2, True, 4, True, 6, True, 8, True, 10]
nums = [x for x in range(11)]
res = map(func, nums) # 参数只有这两个
print(list(res))
# 等价于
all_res = []
for num in nums:
res = func(num)
all_res.append(res) print(filter(lambda x: x > 5, [12, 3, 12, 2, 1, 2, 35])) # 把后面的迭代对象根据前面的方法筛选
# filter:循环调用函数,只保存返回结果为真的
res = filter(func, nums)
# print(list(res)) # return a时,[2, 4, 6, 8, 10] 没有0,是因为return 0 ,0也是假,所以未返回
print(list(res)) # return b时,[0, 2, 4, 6, 8, 10]
''' print(frozenset({1, 2, 3, 3})) # 定义一个不可修改的集合
print(globals()) # 返回程序内所有的全局变量,返回的是一个字典
print(locals()) # 返回局部变量
print(hash('aaa')) # 把一个字符串哈希成一个数字
print(hex(111)) # 0x6f 数字转成16进制
print(max(111, 12)) # 111 取最大值
print(oct(111)) # 0o157 把数字转换成8进制
print(round(11.111111, 2)) # 11.11 取几位小数
print(format(11.11111, '0.2f')) # 11.11
print(sorted([2, 31, 34, 6, 1, 23, 4], reverse=True)) # 排序,默认升序,把reverse的值赋为True,降序排列 '''
# 函数如果有多个return值,那么会把这几个return的值都放到一个元组里面,然后返回
def hello(a, b, c, d):
return a, b, c, d
print(hello('1', '2', '3', '4')) # ('1', '2', '3', '4') # 列表推导式
nums = [0, 1, 2, 3, 4]
new_nums = [str(x) for x in nums]
print(new_nums) # ['0', '1', '2', '3', '4']
'''
2.  处理json
# json:一种通用的数据类型
import json
d = {
'car': {'color': 'red', 'price': 100, 'count': 50},
'挨粪叉': {'color': 'red', 'price': 100, 'count': 50},
'挨粪叉1': {'color': 'red', 'price': 100, 'count': 50},
'挨粪叉2': {'color': 'red', 'price': 100, 'count': 50},
'挨粪叉3': {'color': 'red', 'price': 100, 'count': 50},
'挨粪叉4': {'color': 'red', 'price': 100, 'count': 50},
}
# json.dumps()将list dict转化为json串
res = json.dumps(d, indent=4, ensure_ascii=False)
# fi = open('f.txt', 'w', encoding='utf-8')
# fi.write(res)
# json文件中必须用"",不能用'',否则会报错 # f1 = open('f.txt', 'w', encoding='utf-8')
# 自动将json串写入文件中
# json.dump(d, f1, indent=4, ensure_ascii=False) f1 = open('f.txt', encoding='utf-8')
# 自动将从文件读取的json串转化为python对象
res = json.load(f1)
print(res, type(res))
 3. 模块
  1) 常用模块
import os
# .代表当前路径,..代表上一级路径
# print(os.getcwd()) # 获取当前工作目录#
# os.chmod("/usr/local", 7) # 给文件/目录加权限
# print(os.chdir("../")) # 更改当前目录
# print(os.curdir) # 当前目录
# print(os.pardir) # 父目录
# print(os.makedirs("/usr/hehe/hehe1")) # 递归创建文件夹,父目录不存在时创建父目录
# print(os.removedirs("/usr/hehe/hehe1")) # 递归删除空目录
# print(os.mkdir("test1")) # 创建文件夹
# print(os.rmdir("test1")) # 删除指定的空文件夹
# print(os.remove("test")) # 删除文件
# print(os.listdir('.')) # 列出一个目录下的所有文件
# os.rename("test", "test1") # 重命名
# print(os.stat("笔记")) # 获取文件信息
# print(os.sep) # 当前操作系统的路径分隔符
# print(os.linesep) # 当前操作系统的换行符
# print(os.pathsep) # 当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
# print(os.environ) # 当前系统的环境变量
# print(os.name) # 当前系统名称
# print(__file__) # 获取当前文件的绝对路径 D:/PyCharmWorkspace/bcClassExercises/day5/常用模块.py
# print(os.path.abspath(__file__)) # 获取绝对路径 D:\PyCharmWorkspace\bcClassExercises\day5\常用模块.py
# print(os.path.split("/usr/hehe/hehe.txt")) # 分割路径和文件名 ('/usr/hehe', 'hehe.txt')
# print(os.path.split(r'D:\haha\1.txt')) # ('D:\\haha', '1.txt')
# print(os.path.dirname("/usr/local")) # 获取父目录
# print(os.path.basename("/usr/local")) # 获取最后一级,如果是文件显示文件名,如果是目录显示目录名
# print(os.path.exists("/usr/local")) # 判断目录/文件是否存在
# print(os.path.isabs(".")) # 判断是否是绝对路径
# print(os.path.isfile("/usr/local")) # 判断是否是一个文件
# print(os.path.isdir("/usr/local")) # 是否是一个路径
# print(os.path.join(r"\root", 'hehe', 'a.sql')) # 拼接为一个路径(自动加上\),拼的个数没有限制
# os.system('notepad') # 执行系统命令 # print(os.path.getatime("len_os.py")) # 输出最近访问时间
# print(os.path.getmtime("len_os.py")) # 输出最近访问时间 # os.popen('cmd') 返回的是文件的对象(默认模式r,还可以是w),对其进行读取read()就可以看到输出内容了
# res = os.popen('ipconfig').read() # 执行系统命令,并获取返回结果
# print(res)
# import sys
# print(sys.platform) # 查看当前系统是什么 windows的话都是打印win32
# print(sys.version) # 查看python的版本
# # 获取运行Python文件时,传入的参数
# print(sys.argv) # 命令行参数List,第一个元素是程序本身路径 # sys.exit(n) # 退出程序,正常退出时exit(0)
# quit("程序退出")
# sys.version # 获取Python解释程序的版本信息
# sys.maxint # 最大的Int值
# sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
# sys.platform # 返回操作系统平台名称
# sys.stdout.write('please:') # 向屏幕输出一句话
# val = sys.stdin.readline()[:-1] # 获取输入的值
  2) 时间模块
import time
# time.sleep(1) # 等待几秒
# 1. 格式化好的时间 2018-1-14 16:42
# 2. 时间戳,是从unix元年到现在的所有秒数
# print(int(time.time())) # 当前时间戳
# cur_time = time.strftime('%Y:%m:%d %H:%M:%S') # 获取当前时间的格式化时间字符串
# print(cur_time)
#
#
# print(time.gmtime()) # # 默认获取标准时区的时间元组,如果传入了一个时间戳,那么把这个时间戳转化为时间元组
# print(time.gmtime(1516005840)) # 取的标准时区
# print(time.timezone) # 和标准时间相差了几个小时
# print(time.localtime()) # 默认获取当前时区的时间元组,如果传入一个时间戳,那么把这个时间戳转化为时间元组
#
res = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1515686400))
print(res) # 把格式化好的时间转化为时间戳
t = time.strptime('20180112', '%Y%m%d') # 将参数string按第二个参数format解析为时间元组
print(time.mktime(t)) # 将时间元组转化为时间戳 # 一天的秒数:86400s
# 32342 + 86400*3 or 32342 - 86400*3
# 通过时间戳的加减可以获取几天前几天后的时间
  3) 随机数模块
import random
import string
'''
print(type(string.digits)) # 所有的数字0-9 字符串类型
print(string.ascii_lowercase) # 所有的小写字母
print(string.ascii_uppercase) # 所有的大写字母
print(string.ascii_letters) # 所有的大写字母和小写字母
print(string.punctuation) # 所有的特殊字符 print(random.randint(1, 999)) # 1-999随机取一个整数
print(random.choice(['1', '2', '3', '4'])) # 随机取一个元素,参数是可迭代对象
res = random.sample(string.digits, 3)
print(res)
print(''.join(res))
'''
# 回头查查资料,数字的格式化输出
# random.uniform(1, 9)
res = format(random.uniform(1, 9), '.2f') # 取随机小数
# res = random.uniform(1, 9) # 取随机小数
print(res)
'''
# 5.03203 保留几位小数,四舍五入,如果四舍五入后最后一位小数为0,不显示
# 1.9027236450716112
# 1.9
print(round(res, 2))
print(random.random()) # 取0-1之间的随机小数 s = ['a', 'b', 'c', 'd']
random.shuffle(s) # 洗牌,打乱顺序,参数必须为list
print(s)
'''
  4) 加密模块
import hashlib
# md5
pwd = 'b'
m = hashlib.md5() # 新建一个md5对象
# print(dir(m)) # 打印对象所有的属性和方法
pwd.encode() # 将字符串转成bytes类型
m.update(pwd.encode()) # update() 加密,不能传字符串,只能传二进制bytes类型
print(m.hexdigest()) # 加密后的结果 def md5_passwd(st:str): # 限定入参类型,只能是string类型
bytess = st.encode()
m = hashlib.md5(bytess)
return m.hexdigest()
res = md5_passwd('1')
print(res) # md5加密是不可逆的,不能被解密的。
# MD5 md5AF
# 123456 f0dfb4c968
# 撞库 # 另外一种加密方式
sha_256 = hashlib.sha3_256() import base64
# base64
s = 'hahaha'
bytes_s = s.encode()
res = base64.b64encode(bytes_s)
print(res)
print(res.decode()) # 把bytes类型转成字符串 jie_mi_res = base64.b64decode(res)
print(jie_mi_res.decode())

  

最新文章

  1. GJM : 常用网站收集 【不断更新中... ... ... 】
  2. 如何优化TableView
  3. 大熊君说说JS与设计模式之------代理模式Proxy
  4. 在PowerDesigner中设计物理模型1——表和主外键
  5. 创建高安全性PHP网站的几个实用要点
  6. IOS Swizzle(hook)
  7. 《深入浅出 Java Concurrency》—锁紧机构(一)Lock与ReentrantLock
  8. Microsoft.Identity的IPasswordHasher的默认实现与运用
  9. Java入门之JDK的安装和环境变量的配置
  10. C#使用List实现类似RadioButtonGroup的单选功能
  11. learn
  12. IE 浏览器旧版本下载
  13. Alpha阶段项目规划
  14. 13.纯 CSS 创作一个冒着热气的咖啡杯
  15. P1522 牛的旅行 Cow Tours
  16. unable to find the sources of your current Linux kernel.
  17. H2O中的随机森林算法介绍及其项目实战(python实现)
  18. 微信小程序 跳一跳 外挂 C# winform源码
  19. Openresty增加waf配置
  20. [Python开发工具] Pycharm之快捷键

热门文章

  1. PreparedStatement和Statement区别详解
  2. 为什么gitHub提交记录显示作者名称是unknow?
  3. Koa源码解析
  4. 20145314郑凯杰 《Java程序设计》第4周学习总结
  5. 20135302魏静静——linux课程第四周实验及总结
  6. Mac上Homebrew的使用——Homebrew 使 OS X 更完整
  7. Linux crontab命令 定时任务 用法详解以及no crontab for root解决办法
  8. 从0开始 数据结构 AC自动机 模板(from kkke)
  9. JAXB和XStream比较
  10. SPSS t 检验