1、输入一个列表(里面元素是整型),遍历列表中的数字作为延迟的秒数,延迟后输出当前时间
import time
#使用map函数实现键盘输入列表
lst=list(map(int,input("输入空格间隔数字:").split()))
#写一个循环,遍历列表中的内容
for i in lst:
#使用sleep使程序延迟
time.sleep(i)
#使用strftime将时间转换成正常的格式
time_now=time.strftime("%Y-%m-%d%H:%M:%S ",time.localtime())
print(time_now)
运行结果:(延迟4秒得出结果)
输入空格间隔数字:1 2 3
2020-12-0719:42:33
2020-12-0719:42:35
2020-12-0719:42:38
解析:
list(map(int,input(“输入空格间隔数字:”).split())),该语句通过map可以实现某个函数的批量调用
int指int()函数,强制类型转换
**input().split()**会把输入的字符串数据用空格分隔开。如果输入1 2 3,语句会把它分隔为[‘1’,‘2’,‘3’],map()会调用3次int()函数:int(‘1’),int(‘2’),int(‘3’),然后map()还把int()函数调用的返回值收集起来,把[‘1’,‘2’,‘3’]转换成[1,2,3]
2、分别使用for循环和while循环计算整数1~1000的和,并且比较二者的用时,如果for循环用时短则输出"for win!",如果while循环用时短则输出“while win!”,如果两个循环用时相等则输出“draw!”
import time
#输出当前的时间
print("比赛开始于:",time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()),"\n")
#记录当前系统最高精度的时间
start_time=time.perf_counter()
#设置一个计数器
count_for=0
#定义一个for循环累加的代码
for i in range(1,1001):
#每循环一次,都加上当前i的值
count_for+=i
print("for循环计算的结果为:{}".format(count_for))
#记录结束的时间
end_time=time.perf_counter()
#计算花费的时间
cost_time1=end_time-start_time
#花费的总时长
print("for循环花费的总时间是:{}秒".format(cost_time1))
start_time=time.perf_counter()
count_while=0
#定义一个while循环累加的代码
i=1
while i<1001:
count_while+=i
i+=1
print("while循环计算的结果为:{}".format(count_while))
end_time=time.perf_counter()
cost_time2=end_time-start_time
print("while循环计算的结果为:{}秒".format(cost_time2))
print("for循环花费的时间-while循环花费的时间为:{}秒".format(cost_time1-cost_time2))
if cost_time1-cost_time2>0:
print('\nwhile win!')
elif cost_time1-cost_time2<0:
print('\nfor win!')
else:
print('\ndraw!')
运行结果:
比赛开始于: 2020-12-0720:08:15
for循环计算的结果为:500500
for循环花费的总时间是:0.00014849999999999933秒
while循环计算的结果为:500500
while循环计算的结果为:0.00020440000000000041秒
for循环花费的时间-while循环花费的时间为:-5.590000000000109e-05秒
for win!
time.**perf_counter()**方法具有最高可用分辨率的时钟,以测量短持续时间
perf_counter()会包含sleep()函数产生的睡眠时间,并且是系统范围的时间