簡體   English   中英

除非結果發生變化,否則如何使 while 循環只打印一次結果?

[英]How do I make a while loop print a result just once, unless the result changes?

我做了一個簡短的倒計時程序,從 4 開始倒計時到零,我希望這個倒計時只打印一次每個數字,然后再轉到下一個數字(即 4、3、2、1、0),但它目前多次打印每個數字。

這是我的代碼:

import time

def timer():
    
    max_time = 4
    start_time = time.time()
    while max_time > 0:
        difference = time.time() - start_time

        if 1 > difference > 0:
            print(max_time)
        
        if 2 > difference > 1:
            max_time = 3
            print(max_time)
        
        elif 3 > difference > 2:
            max_time = 2
            print(max_time)
        
        elif 4 > difference > 3:
            max_time = 1
            print(max_time)
        
        elif 5 > difference > 4:
            print('Go')
            break
            
timer()

目前我得到這樣的結果:

4
4
4
4
3
3
3
3
2
2
2
2
1
1
1
1

我想要這樣的結果:

4
3
2
1

謝謝

您的代碼占用了 100% 的 CPU。 那太浪費了。 你通過讓自己睡一會兒來做一個計時器:

import time

def timer():
    max_time = 4
    for i in range(max_time,0,-1):
        print(i)
        time.sleep(1)
    print('Go')
      
timer()

要回答有關一次打印 function 類型的明確問題:我會使用 class 來記住最后打印的內容。 在這里使用上下文管理器( with表達式)很重要,因為打印的最后一行在您完成后不一定會被垃圾收集,否則。

class Printer:
    '''Prints only changed lines'''

    def __init__(self):
        # a new, unique object() is never equal to anything else
        self._last = object()

    def __enter__(self):
        # let with...as statement get to print_once() directly
        return self.print_once

    def __exit__(self, *_):
        # let the last line be garbage collected
        del self._last

    def print_once(self, line):
        '''Print onlt changed line'''
        # don't print the same thing again
        if line != self._last:
            # print the unique thing
            print(line)
            # remember the last thing printed
            self._last = line

with Printer() as print_once:
    for line in [4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1]:
        print_once(line)

相反,如果您只想每秒從 4 倒數一次,請參考 Tim Roberts 的回答。 ;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM