zoukankan      html  css  js  c++  java
  • python 模块一(random,counter,defaultdict,time,wraps,reduce) 栈 队列 双向队列

    ####################总结#######################

    模块:你写的py文件

    引用其他模块

    1.import 模块

    2.from 模块 import 功能,类,变量,函数

    1.random

      random.random() 0-1之间的任意小数
      random.uniform(a,b) a-b之间的随机小数
      random.randint(a,b) a-b随机整数
      random.choice()随机选择一个
      random.sample()随机选择多个

    2.time 时间模块 datetime模块

    1.时间戳(数字形成的时间) time.time()

    2.格式化时间 time.strftime("%Y-%m-%d" %H:%M:%S)

    3.结构化时间 time.localtime()

    数字-->格式化时间

    import time
    num=1232131
    s=time.localtime(num)#先把时间转化成py结构时间 time.strftime("%Y-%m-%d %H:%M:%S",s)

    格式化时间-->数字

    str='2009-01-06 16:40:13'
    struct_time = time.strptime(str, "%Y-%m-%d %H:%M:%S")
     time.mktime(struct_time)
    结果:
    1231231213.0
    datetime模块定义了5个类,分别是
    1.datetime.date:表示日期的类
    
    2.datetime.datetime:表示日期时间的类
    
    3.datetime.time:表示时间的类
    
    4.datetime.timedelta:表示时间间隔,即两个时间点的间隔
    
    5.datetime.tzinfo:时区的相关信息

    datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
    import datetime
    day = datetime.datetime.now()
    ddelay = datetime.timedelta(days=1)
    print(day)
    print(day - ddelay)  # 一天前的时间
    print(day + ddelay)  # 一天后的时间
    print(day - wdelay)  # 5 周前
    print(day + wdelay)  # 5 周后
    
    2019-01-21 22:19:25.705625
    
    >>> print(day.strftime("%Y-%m-%d"))
    2019-01-21

    3. collections (ke lai sheng ri)

    1.defaultdic 默认字典

    >>> from collections import defaultdict
    >>> dd = defaultdict(lambda: 0)
    >>> print(dd["张无忌"])
    0
    >>> print(dd["宝宝"])
    0
    >>> print(dd)
    defaultdict(<function <lambda> at 0x0000000002A3AA60>, {'张无忌': 0, '宝宝': 0})

    2.OrderedDict 排序字典

    >>> from collections import OrderedDict
    >>> dic = OrderedDict()
    >>> dic["b"] = "哈哈"
    >>> dic['a'] = "呵呵"
    >>> print(dic)
    OrderedDict([('b', '哈哈'), ('a', '呵呵')])
    >>> print(dic.get("a"))
    呵呵
    >>> print(dic.values())
    odict_values(['哈哈', '呵呵'])
    >>> print(dic["a"])
    呵呵

    3.Counter 计数器

    >>> from collections import Counter
    >>> print(Counter("宝宝今年特别喜欢王宝强"))
    Counter({'': 3, '': 1, '': 1, '': 1, '': 1, '': 1, '': 1, '': 1,
     '': 1})
    >>> dic = {"a":"哈哈", "b":"哈哈", "c":"车牌"}
    >>> c = Counter(dic.values())
    >>> print(c)
    Counter({'哈哈': 2, '车牌': 1})

    4.deque 双向队列

    Stack 栈
    先进后出(FILO)

    Queue 队列
    先进先出(FIFO)

    ########栈

    class RunException(Exception):
        pass
    class ChuException(Exception):
        pass
    class Stack:
        def __init__(self,size):
            self.size = size
            self.lst = []#存放数据列表
            self.top = 0 #栈顶指针
    #入栈
        def push(self,el):
            if self.top >= self.size:
                raise RunException('入口满了')
            self.lst.insert(self.top,el)#存放元素
            self.top +=1#栈顶指针向上移动一下
    #出栈
        def pop(self):
            if self.top ==0:
                raise ChuException('没有了')
            self.top-=1
            el = self.lst[self.top]
            return el
    s=Stack(6)
    s.push('宝宝1')
    s.push('宝宝2')
    s.push('宝宝3')#入栈传参
    print(s.pop())#出口弹出
    print(s.pop())
    print(s.pop())
    ######################
    宝宝3
    宝宝2
    宝宝1

    ########队列

    import queue
    q=queue.Queue()
    q.put('李嘉诚1')
    q.put('李嘉诚2')
    q.put('李嘉诚3')
    
    print(q.get())
    print(q.get())
    print(q.get())
    
    ##########
    李嘉诚1
    李嘉诚2
    李嘉诚3

    ################双向

    from collections import deque
    d = deque() # 创建双向队列
    d.append("宝宝") #  在右侧添加
    d.append("no")
    d.append("way")
    
    d.appendleft("娃哈哈") # 在左边添加
    d.appendleft("爽歪歪")
    d.appendleft("优酸乳")
    
    
    print(d.pop()) # 从右边拿数据
    print(d.pop()) # 从右边拿数据
    print(d.pop()) # 从右边拿数据
    print(d.pop()) # 从右边拿数据
    print(d.popleft()) # 从左边拿数据
    print(d.popleft()) # 从左边拿数据
    print(d.popleft()) # 从左边拿数据
    ###########结果########
    Traceback (most recent call last):
      File "D:/python_work_s18/day25模块和包/test.py", line 46, in <module>
        print(d.popleft()) # 从左边拿数据
    IndexError: pop from an empty deque
    way
    no
    宝宝
    
    娃哈哈
    优酸乳
    爽歪歪

    5. functools

    1.wraps 装饰器,给inner改名字

    from functools import wraps#可以改变函数的名字
    def wrapper(fn):
        @wraps(fn) #把inner的名字改变成原来的func
        def inner(*args,**kwargs):#为了目标函数传参
            print('')
            ret=fn(*args,**kwargs)#为了调用目标函数,ret返回值
            print('')
            return ret#把目标返回值
        return inner#直接调用innter
    @wrapper
    def func():
        print('哈哈哈')
    print(func.__name__)

    2.reduce 归纳

    print(list(map(lambda x: x**2, [i for i in range(10)])))
    from functools import reduce
    def func(a, b):
        return a + b # 0+1 +4 +7+2+5+8+3+6+9 # 累加
    
    # 会把我们每一个数据交给func去执行, 把默认值作为第一个参数传递给函数
    # 第二个参数就是你这个序列中的第一个数据
    # 接下来. 把刚才返回的结果作为第一个参数传递个a
    # 继续吧刚才的结果给第一个参数. 把第三个数据传递给b
    ret = reduce(func, [1,4,7,2,5,8,3,6,9],0)#可以设置默认参数

    3.偏函数(partial) 固定函数的参数

    #场景 不是你写的代码 你可以执行 加东西

    from functools import partial
    
    def chi(zhushi, fushi):
        print(zhushi, fushi)
    # 固定函数中某些参数的值
    chi2 = partial(chi, fushi="辣鸡爪1")
    chi2("大米饭")
    chi2("小米饭")
    # chi2("黑米饭")
    ######################
    大米饭 辣鸡爪1
    小米饭 辣鸡爪1

    ###################作业###################

    # 1、回顾文件递归遍历. 默写一遍.
    import os
    def func(lujing,n):
        lst=os.listdir(lujing)#打开文件夹,列出所有名字 b c
        for el in lst: #循环当前文件夹名字 b c
            path=os.path.join(lujing,el)#拼接出路径+文件夹 D:/app/zip7-Zip
            if os.path.isdir(path):#判断是不是文件夹
                print('...'* n,el) #如果是文件就打印
                func(path,n+1) #再来一次
            else:
                print("	" * n,el)
    func("D:/app/zip",0)
    
    # 2、写一个copy函数,接受两个参数,第一个参数是源文件的位置,第二个参数是目标位置,将源文件copy到目标位置。
    
    # 3、计算时间差(用户输入起始时间和结束时间. 计算时间差(小时),
    # 例如, 用户输入2018-10-08 12:00:00   2018-10-08 14:30:00 输出2小时30分
    import time
    start_str = input("请输入起始时间(yyyy-mm-dd hh:mm:ss):")
    end_str = input("请输入结束时间(yyyy-mm-dd hh:mm:ss):")
    
    # 结构化时间
    struct_time_start = time.strptime(start_str, "%Y-%m-%d %H:%M:%S")
    struct_time_end = time.strptime(end_str, "%Y-%m-%d %H:%M:%S")
    
    #时间戳
    start = time.mktime(struct_time_start)
    end = time.mktime(struct_time_end)
    
    # 计算时间差
    diff_sec = end - start
    # print(diff_sec)
    diff_min = diff_sec // 60#这个分钟就可以进行计算金额了
    
    # 计算小时,  显示的分钟
    diff_hour_display = int(diff_min // 60)#显示小时
    diff_min_display = int(diff_min % 60)#分钟
    
    print(f"经过了{diff_hour_display}小时{diff_min_display}分钟")
    
    # 4、使用random.random()来计算[m,n]以内的随机整数
    import  random
    def a(m,n):
        ret = int(random.random() * (m - n + 1) + n)
        return ret
    ret=a(20,18)
    print(ret)
    
    # 5、写一个用户注册登陆的程序,每一个用户的注册都要把用户名和密码用字典的格式写入文件userinfo。在登陆的时候,再从文件中读取信息进行验证。
    #
    # 注册
    # username = input("请输入你的用户名:")
    # userpwd = input("请输入你的密码:")
    #
    # dic = {"username":username, "userpwd":userpwd}
    #
    # f = open("userinfo", mode="a", encoding="utf-8")
    # f.write(str(dic)+"
    ")
    # f.flush()
    # f.close()
    
    # 登录
    username = input("请输入你用户名:")
    password = input("请输入你密码:")
    
    f = open("userinfo", mode="r", encoding="utf-8")
    for line in f:
        d = eval(line.strip())
        if username == d['username'] and password == d['userpwd']:
            print("登录成功")
            break
    
    else:
        print("登录失败")
    
    f.close()
    
    
    
    # 明日默写内容:
    #
    # 1. 时间戳转换成格式化时间
    import time
    a=1545829865.6255307
    t=time.localtime(a)#先把这个时间转化成python中的结构化时间
    s=time.strftime("%Y-%y-%d %H:%M:%S")
    print(s)
    
    # 2. 格式化时间转换成时间戳
    
    import time
    s='2019-09-09 12:10:10'
    #把用户户儒的字符串转换成结构化时间
    st=time.strptime(s,'%Y-%m-%d %H:%M:%S')
    #转换成时间戳
    num=time.mktime(st)
    print(num)
    # 3. 通用装饰器(带wraps) from functools import wraps def wrapper(fn): @wraps(fn)#把inner的名字改成原来的dunc def inner(*args,**kwargs): print('前') res=fn(*args,*kwargs) print('后') return res return inner @wrapper def func(): print('hahah') print(func.__name__)
     
    不怕大牛比自己牛,就怕大牛比自己更努力
  • 相关阅读:
    python 判断矩阵中每行非零个数的方法
    用Python 绘制分布(折线)图
    统计numpy数组中每个值出现的个数
    pandas 获取不符合条件的dataframe
    Python 中如何判断 list 中是否包含某个元素
    docker与Spring boot的集成:docker-maven-plugin使用
    处理kdevtmpfsi挖矿病毒
    使用docker-maven-plugin推送镜像到远程docker服务器
    docker 开启2375端口,提供外部访问docker
    Spring Boot 配置优先级顺序
  • 原文地址:https://www.cnblogs.com/zaizai1573/p/10182657.html
Copyright © 2011-2022 走看看