--------------3

Random模块:

#!/usr/bin/env python
#_*_encoding: utf-8_*_
import random
print (random.random())  #0.6445010863311293  
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print (random.randint(1,7)) #4
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print (random.randrange(1,10)) #5
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print(random.choice('liukuni')) #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print(random.choice("学习Python"))#
print(random.choice(["JGood","is","a","handsome","boy"]))  #List
print(random.choice(("Tuple","List","Dict")))   #List
print(random.sample([1,2,3,4,5],3))    #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

#############Random模块实际应用##########
#随机整数:
print( random.randint(0,99))  #70
 
#随机选取0到100间的偶数:
print(random.randrange(0, 101, 2)) #4
 
#随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844
 
#随机字符:
print(random.choice('abcdefg&#%^*f')) #f
 
#多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd']
 
#随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]

 json模块:

'''
json模块
1、把内存中的数据类型序列化为字符串或者字符串反序列化
2、用于不同的平台之间的数据交换,所以序列化的对象类型应是通用的
例如:字符串、列表、字典
3、一次dump,一次load
'''

#################json序列化#################
import json
f = open('test.txt','w')
info = {'name':'alex','age':22}
json.dump(info,f)   #等价于 f.write(json.dumps(info))
f.close()           #test.txt中存放{'name': 'alex', 'age': 22}
#################json反序列化#################
f = open('test.txt','r')
data = json.load(f)  #等价于 f.loads(f.read())
print(data['name'])      # alex

 pickle模块:

'''
pickle模块:
1、只能Python中使用
2、可存放所有对象
3、一次dump,一次load
'''
##################pickle序列化##################
import pickle
def sayhi(name):
    print('hello',name)
info = {'func':sayhi}
f = open('test.txt','wb')
pickle.dump(info,f)  # 或者 f.write(pickle.dumps(info))
f.close()            # 序列化为二进制文件
##################pickle反序列化##################
f = open('test.txt','rb')
data = pickle.load(f)       # 或者pickle.loads(f.read())
data['func']('alex')        # hello,alex

 shelve模块:

'''
shelve模块
可以让你一次dump很多对象,取的时候按名称取。shelve是对pickle更上一层的封装
'''

import shelve
import datetime
#####################序列化#######################
d = shelve.open("test")
info = {'name':'alex','age':22}
pets = {'dog','cat'}
d['info'] = info
d['pets'] = pets
d['date'] = datetime.datetime.now()

#####################反序列化#######################
d = shelve.open("test")
print(d.get('info'))        # {'name': 'alex', 'age': 22}
print(d.get('pets'))        # {'dog', 'cat'}
print(d.get('date'))        # 2018-07-17 22:43:41.091981

 time模块

'''
时间的表示格式:
1、格式化字符串"2018-07-01 13:45:557"
2、时间戳,从1970-1-1到现在的秒数1531908307.0743685
3、元祖,time.localtime() 年月日时分秒等元素
时区UTC+8
'''
import time
time.time()  #获取时间戳,float
time.sleep(2) #暂停2毫秒
time.gmtime(1000) #时间戳1000秒==>为元祖的表示形式UTC
time.localtime(1000) #时间戳1000秒==>为元祖表示形式UTC+8
time.mktime(tuple)  #传入元祖==>时间戳
time.strftime("%Y-%m-%d",tuple)  #元祖==>格式化字符串
time.strptime("2016-09-02","%Y-%m-%d") #格式化字符串==>为元祖
time.asctime(tuple)  #把元祖==>Sat Aug 20 14:59:45 2016格式表示
time.ctime(3232342) #把时间戳==>Sat Aug 20 14:59:45 2016格式表示

datetime模块

import datetime

print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
print(datetime.datetime.now() )
print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

c_time  = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换

猜你喜欢

转载自www.cnblogs.com/staff/p/9271912.html
3
3-3