添加到列表中的值时出现问题。[Python2.7.10]

2024-09-29 17:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎不能增加时间。我试着用单子做一个钟。快进时钟

谢谢你的帮助!问题将出现在第一个“if”语句中

import random
import time

ctime = [10, 00] #current_time
#s = random.uniform(.3,1)
s = float(.01)

while True:
      if ctime[1] == 59:
            time.sleep(s)
            ctime.remove(ctime[1])
            ctime.insert(00,1)
            nhour = int(ctime[0]+1) #next_hour
            ctime.insert(nhour, 0)
      elif ctime[0] == 23 and ctime[1] == 59:
            ctime.remove(ctime[0 and 1])
            ctime.insert(00)
            ctime.insert(00)
      else:
            ctime[1]+=1
            time.sleep(s)
      print(ctime)

更新:

忘了给你看输出,对不起。它照常继续,分钟从0到59,然后回到0,但是小时变为02,即使在分钟过去后仍然保持为02


Tags: andimportiftime时间sleeprandom语句
2条回答

你使用了错误的数据结构。列表用于移动一堆相似的项目,以便每个项目都可以单独处理。这是一个收藏。那不是你要做的。你试着把一组东西,当作一个单元来对待,这个单元有已知的相互作用

你需要的是上课。Python已经包含了many date/time classes,但是我们可以继续这样实现您的用例,只是为了举例说明

class Ticker(object):
    def __init__(self, hour, minute):
        self.hour = hour
        self.minute = minute

    def tick(self):
        self.minute = (self.minute + 1) % 60
        self.hour = (self.hour + 1) % 24 if self.minute == 0 else self.hour

现在你的循环简单多了

ticker = Ticker()
while True:
    print("%d:%d" % (ticker.hour, ticker.minute))
    time.sleep(s)
    ticker.tick()

我想你把你的论点顺序弄糊涂了

https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

编辑:对不起,忘记做实际更正

试试ctime.insert(1,0)

还有ctime.insert(0, nhour)

相关问题 更多 >

    热门问题