前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3--模块collections,time,random,sys

python3--模块collections,time,random,sys

作者头像
py3study
发布2018-08-02 16:29:15
4190
发布2018-08-02 16:29:15
举报
文章被收录于专栏:python3python3

defaultdict(默认字典)

有如下值集合[11,22,33,44,55,66,77,88,99,90......],将所有大于66的值保存至字典的第一个key中,小于66的值保存至第二个key的值中

即:{'k1':大于66,'k2':小于66}

代码语言:javascript
复制
values = [11,22,33,44,55,66,77,88,99,90]
dic = {}
for i in values:
    if i > 66:
        if dic.get('k1'):
            dic['k1'].append(i)
        else:
            dic['k1'] = [i]
    elif i < 66:
        if dic.get('k2'):
            dic['k2'].append(i)
        else:
            dic['k2'] = [i]
print(dic)

执行结果

{'k2': [11, 22, 33, 44, 55], 'k1': [77, 88, 99, 90]}

使用defaultdict解题

代码语言:javascript
复制
from collections import defaultdict
values = [11,22,33,44,55,66,77,88,99,90]
dic = defaultdict(list)
for i in values:
    if i > 66:
        dic['k1'].append(i)
    elif i < 66:
        dic['k2'].append(i)
print(dic)

执行结果

defaultdict(

使用dict时,如果引用的key不存在,就会抛出keyerror,如果希望key不存在时,返回一个默认值,就可以用defaultdict

代码语言:javascript
复制
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print(dd['key1'])
print(dd['key2'])  # k2不存在,返回默认值

执行结果

abc

N/A

counter

counter类的目的是用来跟踪值出现的次数,它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value.计数值可以使任意的interger(包括0和负数)

代码语言:javascript
复制
from collections import Counter
c = Counter('abcdeabcdabcadacbaa')
print(c)

执行结果

Counter({'a': 7, 'c': 4, 'b': 4, 'd': 3, 'e': 1})

time时间模块

和时间有关系的我们就要用到时间模块,在使用模块之前,应该首先导入这个模块

常用方法

1 time.sleep(secs)

(线程)推迟指定的时间运行,单位为秒

2 time.time()

获取当前时间戳

表示时间的三种方式

在python中,通常有三种方式来表示时间:时间戳,元组(struct_time),格式化的时间字符串

1 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型

2 格式化的时间字符串(Format String): '1999-12-06'

%y 两位数的年份表示(00-99)

%Y 四位数的年份表示(000-9999)

%m 月份(01-12)

%d 月内中的一天(0-31)

%H 24小时制小时数(0-23)

%I 12小时制小时数(01-12)

%M 分钟数(00=59)

%S 秒(00-59)

%a 本地简化星期名称

%A 本地完整星期名称

%b 本地简化的月份名称

%B 本地完整的月份名称

%c 本地相应的日期表示和时间表示

%j 年内的一天(001-366)

%p 本地A.M.或P.M.的等价符

%U 一年中的星期数(00-53)星期天为星期的开始

%w 星期(0-6),星期天为星期的开始

%W 一年中的星期数(00-53)星期一为星期的开始

%x 本地相应的日期表示

%X 本地相应的时间表示

%Z 当前时区的名称

%% %号本身

3 元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

blob.png
blob.png

导入time模块,来认识一下python中表示时间的几种格式

代码语言:javascript
复制
import time

# 时间戳
print(time.time())

# 格式化时间
print(time.strftime("%Y-%m-%d"))  # 字符串格式化时间
print(time.strftime("%Y-%m-%d %H-%M-%S"))  # 字符串格式化时间
print(time.strftime('%x %X'))  # 字符串格式化时间
print(time.strftime('%c'))  # 字符串格式化时间

# 结构化时间
print(time.localtime())  # 本地结构化时间
print(time.gmtime())  # 英国的结构化时间

执行结果

1524567428.2425647

2018-04-24

2018-04-24 18-57-08

04/24/18 18:57:08

Tue Apr 24 18:57:08 2018

time.struct_time(tm_year=2018, tm_mon=4, tm_mday=24, tm_hour=18, tm_min=57, tm_sec=8, tm_wday=1, tm_yday=114, tm_isdst=0)

time.struct_time(tm_year=2018, tm_mon=4, tm_mday=24, tm_hour=10, tm_min=57, tm_sec=8, tm_wday=1, tm_yday=114, tm_isdst=0)

时间戳转换

blob.png
blob.png
代码语言:javascript
复制
import time
p = time.strptime('2015-8-8', '%Y-%m-%d')
print(time.mktime(p))  # 格式化时间转换时间戳

ret = time.localtime(1500000000)
print(time.strftime('%Y-%m-%d %H:%M:%S', ret))  # 时间戳转格式化时间

# 结构化时间转格式化时间
# time.strftime
print(time.strftime("%Y-%m-%d", time.localtime(1500000000)))  # 年-月-日
print(time.strftime("%Y-%m-%d, %H:%M:%S", time.localtime(1500000000)))  # 年-月-日 时:分:秒

# 格式化时间-->结构化时间
# time.strptime(时间字符串,字符串对应格式)
print(time.strptime("2018-04-24", "%Y-%m-%d"))
print(time.strptime("04/24/2018", "%m/%d/%Y"))

执行结果

1438963200.0

2017-07-14 10:40:00

2017-07-14

2017-07-14, 10:40:00

time.struct_time(tm_year=2018, tm_mon=4, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=114, tm_isdst=-1)

time.struct_time(tm_year=2018, tm_mon=4, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=114, tm_isdst=-1)

blob.png
blob.png

结构化时间----->%a %b %d %H:%M:%S(格式化时间)

time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串

代码语言:javascript
复制
import time
print(time.asctime(time.localtime(1500000000)))  # 指定时间
print(time.asctime())  # 当前时间

执行结果

Fri Jul 14 10:40:00 2017

Tue Apr 24 19:42:41 2018

时间戳-----> %a %b % d %H:%M:%S(格式化时间)

time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串

代码语言:javascript
复制
import time
print(time.ctime())  # 当前时间
print(time.ctime(1500000000))  # 指定时间

执行结果

Tue Apr 24 19:46:51 2018

Fri Jul 14 10:40:00 2017

练习:

计算从当前时间开始,比起Y-m-d H:M:S 过去了多少年,多少月,多少天,多少小时,多少分钟,多少秒?

代码语言:javascript
复制
import time
true_time=time.mktime(time.strptime('2018-04-23 08:30:00','%Y-%m-%d %H:%M:%S'))
time_now=time.mktime(time.strptime('2018-04-24 11:00:00','%Y-%m-%d %H:%M:%S'))
dif_time=time_now-true_time
struct_time=time.gmtime(dif_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
                                       struct_time.tm_mday-1,struct_time.tm_hour,
                                       struct_time.tm_min,struct_time.tm_sec))

执行结果

过去了0年0月1天2小时30分钟0秒

random模块

代码语言:javascript
复制
import random
print(random.random())  # 大于0且小于1之间的小数
print(random.uniform(1, 3))  # 大于1小于3的小数
print(random.randrange(1, 5))  # 大于等于1且小于等于5之间的数
print(random.randrange(1, 10, 2))  # 大于等于1且小于10之间的奇数

# 随机整数
print(random.randint(1, 5))  # 大于等于1且小于等于5之间的整数

# 随机选择一个返回
print(random.choice([1, '23', [4, 5]]))  # 1或者'23'或者[4,5]

# 随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1, '23', [4, 5]], 2))  # 列表元素任意两个组合

# 打乱列表顺序
item = [1, 3, 5, 7, 9]
random.shuffle(item)  # 打乱次序
print(item)

执行结果

0.024784575662495034

2.3860472857875683

3

3

2

23

[[4, 5], '23']

[5, 3, 7, 1, 9]

练习:

要求,生成随机验证码

基础需求: 6位数的验证码,数字可以重复

代码语言:javascript
复制
import random
new_list = []
for i in range(6):
    new_list.append(str(random.randrange(1, 9)))
ss = ''.join(new_list)
print(ss)

执行结果

174635

方法2

代码语言:javascript
复制
import random
# 函数传参的方式
def id_code(num):
    ret = ''
    for i in range(num):
        n = str(random.randint(0, 9))
        ret += n
    return ret
print(id_code(6))

执行结果

334858

进阶需求: 字母+数字 4位验证码,数字字母都可以重复

代码语言:javascript
复制
import random
new_list = []
for i in range(1, 10):  # 数字1到9
    new_list.append(str(i))
for i in range(65,91):  # 大写字母
    new_list.append(chr(i))
new_list = random.sample(new_list, 4)
ss = ''.join(new_list)
print("生成的随机验证为:{}".format(ss))
while True:
    content = input('输入验证码:').strip().upper()
    if content == ss:
        print('验证成功')
        break
    else:
        print('验证失败')

执行结果

生成的随机验证为:QSCY

输入验证码:qscy

验证成功

方法2:

代码语言:javascript
复制
import random
def id_code(num):
    ret = ''
    for i in range(num):
        number = str(random.randint(0, 9))  # 数字 0 - 9
        alph_num1 = random.randint(97, 122)  # 数字 97 - 122 (ascii对应a - z)
        alph_num2 = random.randint(65, 90)   # 数字 65 - 90  (ascii对应A - Z)
        alph1 = chr(alph_num1)  # 利用chr把对应的数字转成小写字母
        alph2 = chr(alph_num2)  # 利用chr把对应的数字转成大写字母
        choice = random.choice([number, alph1, alph2])
        ret += choice
    return ret

def content():
    id_code_num = id_code(6)
    print('随机验证为:{}'.format(id_code_num))
    while True:
        ss = input("输入验证码:").strip().upper()
        if ss == id_code_num.upper():
            print('验证成功')
            break
        else:
            print('验证失败')
content()

执行结果

随机验证为:7GfM01

输入验证码:tgfm01

验证失败

输入验证码:7gfm01

验证成功

sys模块

sys模块是与python解释器交互的一个接口

sys.argv           命令行参数List,第一个元素是程序本身路径

sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)

sys.version        获取Python解释程序的版本信息

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform       返回操作系统平台名称

退出程序

代码语言:javascript
复制
import sys
print('*'*10)
sys.exit()  # 退出程序,后面的不会被执行
print('*'*10)

执行结果

**********

代码语言:javascript
复制
import sys
print(sys.version)  # 打印python版本
print(sys.platform)  # 打印系统版本(win or mac or linux)
print(sys.path)  # 打印路径

执行结果

blob.png
blob.png

sys.argv

创建一个新的py文件,命名为sys_argv.py

里面内容如下

import sys

print(sys.argv)

在cmd里面执行,进入当前文件目录,如图

blob.png
blob.png

执行: python sys.argv.py 命令

返回当前文件名路径

blob.png
blob.png

执行: python D:/python11_quanzhan/day27/sys_argv.py 命令

返回当前文件名绝对路径

blob.png
blob.png

执行: python D:/python11_quanzhan/day27/sys_argv.py sam 123456 命令

返回当前文件名绝对路径加输入的参数

blob.png
blob.png

编写sys.argv.py文件

代码语言:javascript
复制
import sys
print(sys.argv)

user = input('输入账号').strip()
pwd = input('输入密码').strip()

if sys.argv[1] == 'sam' and sys.argv[2] == '123456':
    print('登陆成功')
else:
    sys.exit()
print('我能完成的功能')

在cmd里面执行 python sys_argv.py sam 123456 命令

blob.png
blob.png

sys.argv + logging 示例

代码语言:javascript
复制
import sys
import logging

lev = sys.argv[1] if len(sys.argv) > 1 else 'WARNING'
logging.basicConfig(level=getattr(logging, lev))
num = int(input('>>>').strip())
logging.debug(num)
a = num * 100
logging.debug('{}*100={}'.format(num, a))
b = a - 10
logging.debug('{}-10={}'.format(a, b))
c = b + 5
logging.debug('{}+5={}'.format(b, c))
print(c)

在cmd里面执行 python sys_argv.py 命令

blob.png
blob.png

在cmd里面执行 python sys_argv.py DEBUG 命令

blob.png
blob.png

DEBUG打印出每个步骤,方便排错,也方便记录

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档