python列表 延时 循环操作
本帖最后由 weizhiyong21 于 2015-04-30 17:42 编辑本人想写个脚本,如上所述
实时输出的功能自己已经写好了,但是关于输出的值,自己没有想到好的方法。
询问了别人,目前有两个解决办法:
1.将value每次输出到tmp文件中,然后每次取值时,使用tail -n 3 tmp
2.建一个空列表,每次往后面添加value,每次取值时去列表最后三个 //本人自己解决刚开始的索引边界问题
以上两个方法目前都可用,但是我的想法是:
一个空list,每一秒,添加一次value,等到 len(list) = 3的时,之后的每次循环就是删除list的第一个元素,然后后面再添加一个新的元素。
如下:
给定value为1
list_t=[]
list_t= //第1秒
list_t= //第2秒
list_t= //第3秒
list_t= //第4秒
list_t= //第5秒
list_t= //第6秒
求大神用py写出来下。 from time import sleep
GIVENNUM = 1
def cu(lst = []):
lst.append(lst and lst[-1]+1 or GIVENNUM)
if len(lst) > 3:
lst.pop(0)
yield lst
for i in range(20):#20是你想执行的次数
for line in cu():
for j in line:
print(j)
print('================')
sleep(1) from time import sleep
GIVENNUM = 1
def cu(lst = ):
if len(lst) > 3:
lst.pop(0)
yield lst
lst.append(lst[-1] + 1)
for i in range(20):#20是你想执行的次数
for line in cu():
for j in line:
print(j)
print('================')
sleep(1)修改了一下,不需要每次都运行这个判断语句“lst and lst[-1]+1 or GIVENNUM”,能够提高一点效率吧。 #coding:utf-8
import time
t_list=[]
def get_time(S):
global t_list
if len(t_list) <= 2:
t_list.append(S)
return t_list
else:
t_list.append(S)
t_list.remove(t_list)
def mainf():
S=time.strftime('%H:%M:%S', time.localtime())
get_time(S)
time.sleep(1)
print t_list
mainf()
if __name__ == '__main__':
mainf()
图片是脚本的执行效果,,为了便于理解,发帖子时改成数字了,
这是昨天下班的一瞬间想到了,,
哈哈,谢谢了,我自己昨天想到了怎么实现,你的方法也是也用的。
回复 3# ssfjhh
#coding:utf-8
import time
t_list=[]
def get_time(S):
if len(t_list) <= 2:
t_list.append(S)
return t_list
else:
t_list.append(S)
t_list.pop(0)
def mainf():
S=time.strftime('%H:%M:%S', time.localtime())
get_time(S)
time.sleep(1)
print t_list
mainf()
if __name__ == '__main__':
mainf()
稍微修改了下 本帖最后由 liion631818 于 2015-05-01 15:24 编辑
#!/usr/bin/env python
'''
my python exercise
'''
import time
QUEUE_MAX_ITEM = 3
queue = []
def enQ(item):
'''
enter the queue
'''
queue.append(item)
def delQ():
'''
remove from queue
'''
queue.pop(0)
def show():
'''
show queue
'''
print queue
if __name__ == '__main__':
init_time = 1
while True:
enQ(init_time)
time.sleep(1)
if len(queue) > QUEUE_MAX_ITEM:
delQ()
init_time += 1
show()
回复 1# weizhiyong21
回复 7# liion631818
赞~ 很规范!
页:
[1]