简体   繁体   English

Python中轮流使用time.sleep打印两个列表

[英]Printing two lists by taking turns and using time.sleep in Python

I have two lists: [1,2,3,4,5] and ['a','b','c','d','e','f'] .我有两个列表: [1,2,3,4,5]['a','b','c','d','e','f'] (Note that one has 5 items, the other 6). (请注意,一个有 5 个项目,另一个有 6 个)。 What I want is to print them, item-by-item, taking turns, with a one-second delay, each list on its own line.我想要的是逐项打印它们,轮流,延迟一秒,每个列表在自己的行上。 I would imagine the code for printing one list to be something like this:我想打印一个列表的代码是这样的:

import time
for x in [1,2,3,4,5]:
    print(x, end=' ')
    time.sleep(1)

But, after each digit appears in the output, I want a letter to appear underneath it, with a 1 second delay, so that the printing order would be: 1-a-2-b-3-c... , and the end result would look as follows:但是,在 output 中出现每个数字后,我希望在其下方出现一个字母,延迟 1 秒,以便打印顺序为: 1-a-2-b-3-c... ,并且最终结果如下所示:

1 2 3 4 5 
a b c d e f 

Is there a way to make it happen in Python?有没有办法让它在 Python 中发生?

import time
# import os
from IPython.display import clear_output
a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e', 'f']

line_one = ''
line_two = ''
for i1, i2 in zip(a, b):
    # os.system('CLS')
    clear_output(wait=True)
    line_one += (str(i1)+" ")
    print(line_one, end="\n")
    print(line_two, end="", flush=True)
    line_two += (i2+" ")
    time.sleep(1)
    print(i2, end=" ", flush=True)
    time.sleep(1)
for i in range(len(b)-len(a)):
    print(b[len(a)+i],end=" ",flush=True)
    time.sleep(1)

This code should work in jupyter notebook.此代码应该在 jupyter notebook 中工作。 for windows command line, you can use os.system('CLS') instead of clear_output() .对于 windows 命令行,您可以使用os.system('CLS')代替clear_output()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM