zoukankan      html  css  js  c++  java
  • collection模块(具名元组、队列、有序字典、默认值字典)、time 模块、随机模块:random、os模块、sys模块、序列化模块

    collection模块

    1.具名元组:

    用法:namedtuple('标题','容器类型')#第二个参数除了是可迭代对象之外还可以是字符串,但是字符串之间要用空格隔开。

    card = collections.namedtuple('扑克牌','color num')

    #card = collections.namedtuple('扑克牌',['color','num'])#等价于上
    A = card('红心','A')#注意元素个数要与namedtuple第二个参数中元素个数一致
    print(A)
    print(A.color)
    print(A.num)

    #结果

    扑克牌(color='红心', num='A')
    红心
    A

    2.队列:先进先出(FIFO first in first out)

    普通队列:

    import queue
    res = queue.Queue()# 生成队列对象

    res.put('zhao')#往队列中添加值
    res.put('qian')
    res.put('sun')
    print(res.get())#从队列中取值
    print(res.get())
    print(res.get())
    print(res.get())#当队列中值被取完时,程序没有结束,在原地等待直到从队列中取到值为止

    双端队列:

    缺点:可以通过索引在任意位置插值,不应该支持这种行为,不能插队。

    常用方法:(append,appendleft)、(pop,popleft)、insert

    res = collections.deque([])
    res.append('yang')
    res.append('yong')
    res.appendleft('jun')

    res.insert(1,'弟弟')

    print(res)

    #结果:

    deque(['jun', '弟弟', 'yang', 'yong'])

    3、有序字典:

    normal_d = dict([('a',1),('b',2),('c',3)])
    print(normal_d)
    order_d = collections.OrderedDict([('a',1),('b',2),('c',3)])
    print(order_d)
    for i in order_d:
    print(i)

    #结果:

    {'a': 1, 'b': 2, 'c': 3}
    OrderedDict([('a', 1), ('b', 2), ('c', 3)])
    a
    b
    c

    4、默认值字典:

    defaul_d = collections.defaultdict(list)#参数中存放的是数据类型,可以是int,bool,tuple等
    l = [11,22,33,44,55,66,77,88,99]
    for i in l:
    if i >66:
    defaul_d['大于66'].append(i)
    else:
    defaul_d['小于66'].append(i)
    print(defaul_d)

    #结果:

    defaultdict(<class 'list'>, {'小于66': [11, 22, 33, 44, 55, 66], '大于66': [77, 88, 99]})

    5、Counter:统计字符串中各个字符出现的个数,并以键值对的形式放在字典中。

    from collections import Counter
    s = 'fadfavcvafdsaf'
    res = Counter(s)
    print(res)
    for i in res:
    print(i,end='')

    #结果:

    Counter({'f': 4, 'a': 4, 'd': 2, 'v': 2, 'c': 1, 's': 1})
    fadvcs

    time 模块

    有三种表现形式:

    1、时间戳

    2、格式化时间

    3、结构化时间

    import time
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    print(time.localtime(time.time()))

     datatime模块:自定义日期

    import datetime
    print(datetime.date.today()) # date>>>:年月日
     print(datetime.datetime.today()) # datetime>>>:年月日 时分秒

     #结果:

    2019-07-18
    2019-07-18 18:42:42.442004

    res = datetime.date.today()

    print(res.weekday()) # 0-6表示星期 0表示周一

    print(res.isoweekday()) # 1-7表示星期 7就是周日

    """
    (******)
    日期对象 = 日期对象 +/- timedelta对象
    timedelta对象 = 日期对象 +/- 日期对象
    """
    current_time = datetime.date.today() # 日期对象
    timetel_t = datetime.timedelta(days=7) # timedelta对象,定义操作时间 days=7 也就是可以对另一个日期对象加7天或者减少7点
    print(timetel_t)
    res1 = current_time+timetel_t # 日期对象

    print(current_time - timetel_t)
    print(res1-current_time)

    # 小练习 计算举例今年过生日还有多少天

    birthday = datetime.date(2019, 12, 21)

    now_date = datetime.date.today()

    days = birthday - now_date print('生日:{}'.format(birthday))

    print('今天的日期:{}'.format(tday))

    print('距离生日还有{}天'.format(days))

    # UTC时间
    dt_today = datetime.datetime.today()
    dt_now = datetime.datetime.now()
    dt_utcnow = datetime.datetime.utcnow()
    print(dt_utcnow,dt_now,dt_today)

    #结果:

    2019-07-18 10:51:31.618806

    2019-07-18 18:51:31.618806

    2019-07-18 18:51:31.618807

    随机模块:random

    import random
    res = random.randint(0,9)  #随机一个你提供的整数范围内的数字
    print(res)
    res1 = random.random()  #0---1之间的数字
    print(res1)
    res2 = random.choice([1,2,3,4,5,6])  #在列表中随机一个值
    print(res2)
    l = [1,2,3,4,5,6]
    random.shuffle(l)  #随机洗牌
    print(l)

    重点(******):

    #生成随机验证码练习:

    def get_code(n):
    code = ''
    for i in range(n):
    upper_str = chr(random.randint(65,90))
    lower_str = chr(random.randint(97,122))
    num_int = str(random.randint(0,9))
    code += random.choice([upper_str,lower_str,num_int])
    return code
    res = get_code(4)
    print(res)

    os模块:

    # os模块:跟操作系统打交道的模块(与操作系统交互的一个接口)
    # sys模块:跟python解释器打交道模块

    os.makedirs('dirname1/dirname2')    可生成多层递归目录
    os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove()  删除一个文件
    os.rename("oldname","newname")  重命名文件/目录
    os.stat('path/filename')  获取文件/目录信息
    
    os.system("bash command")  运行shell命令,直接显示
    os.popen("bash command).read()  运行shell命令,获取执行结果
    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
    
    os.path
    os.path.abspath(path) 返回path规范化的绝对路径
    os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是绝对路径,返回True os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 os.path.getsize(path) 返回path的大小



    分析:
    # BASE_DIR = os.path.dirname(__file__)

    # MOVIE_DIR = os.path.join(BASE_DIR,'老师们的作品')
    # movie_list = os.listdir(MOVIE_DIR)
    # while True:
    # for i,j in enumerate(movie_list,1):
    # print(i,j)
    # choice = input('你想看谁的啊(今日热搜:tank老师)>>>:').strip()
    # if choice.isdigit(): # 判断用户输入的是否是纯数字
    # choice = int(choice) # 传成int类型
    # if choice in range(1,len(movie_list)+1): # 判断是否在列表元素个数范围内
    # # 获取用户想要看的文件名
    # target_file = movie_list[choice-1]
    # # 拼接文件绝对路径
    # target_path = os.path.join(MOVIE_DIR,target_file)
    # with open(target_path,'r',encoding='utf-8') as f:
    # print(f.read())

    sys模块:

    import sys
    # sys.path.append() # 将某个路径添加到系统的环境变量中
    # print(sys.platform)
    # print(sys.version) # python解释器的版本

    print(sys.argv) # 命令行启动文件 可以做身份的验证
    if len(sys.argv) <= 1:
    print('请输入用户名和密码')
    else:
    username = sys.argv[1]
    password = sys.argv[2]
    if username == 'jason' and password == '123':
    print('欢迎使用')
    # 当前这个py文件逻辑代码
    else:
    print('用户不存在 无法执行当前文件')

    序列化模块:

    序列:字符串

    序列化:其他数据类型转化为字符串的过程

    反序列化:字符串转化成其它数据类型的过程

    写入文件的数据都是字符串类型的,基于网络传输的数据必须是二进制的

    json模块(******):

    优点:所有的语言都支持json

    缺点:支持的数据类型较少,字符串,列表,字典,整型,布尔值,元组(转成列表)

    pickle模块:

    优点:支持所有python所有的数据类型

    缺点:只支持python

    dumps和loads的用法:

    import json
    d = {'yang':21,'zhao':22}
    res = json.dumps(d)
    print(res,type(res))
    res1 = json.loads(res)
    print(res1,type(res1))

    dump和load的用法:

    d = 123
    # with open(r'test','w',encoding='utf-8')as f:
    # json.dump(d,f)
    with open(r'test','r',encoding='utf-8')as f:
    res = json.load(f)
    print(res,type(res))

    中文转换成字符串时:

    d1 = {'name':'杨永军'}
    print(json.dumps(d1))

    #结果:

    {"name": "\u6731\u5fd7\u575a"}

    d1 = {'name':'杨永军'}
    print(json.dumps(d1,ensure_ascii=False))

    结果:

    {"name": "杨永军"}

    subprocess模块:

    """
    1.用户通过网络连接上了你的这台电脑
    2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
    3.获取用户命令 里面subprocess执行该用户命令
    4.将执行结果再基于网络发送给用户
    这样就实现 用户远程操作你这台电脑的操作
    """
    # while True:
    # cmd = input('cmd>>>:').strip()
    # import subprocess
    # obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    # # print(obj)
    # print('正确命令返回的结果stdout',obj.stdout.read().decode('gbk'))
    # print('错误命令返回的提示信息stderr',obj.stderr.read().decode('gbk'))

  • 相关阅读:
    DP问题之最长非降子序列
    CentOS 6.8 编译安装MySQL5.5.32
    [Linux] killall 、kill 、pkill 命令详解
    编写登陆接口
    python学习day01
    python购物车程序
    ERROR:Attempting to call cordova.exec() before 'deviceready'
    BSF脚本引擎‘改变’Bean
    Solr安装配置
    amchart配置备忘
  • 原文地址:https://www.cnblogs.com/yangjiaoshou/p/11209866.html
Copyright © 2011-2022 走看看