Python 如何将睡眠插入列表

Python 如何将睡眠插入列表,python,sleep,Python,Sleep,我希望创建一个小模块来实现文本滚动的功能。到目前为止,我已经尝试了一些方法,这就是我所坐的: from time import sleep def text_scroll(x): x = x.split() #here is where I'd like to add the sleep function x = " ".join(x) print x text_scroll("hello world.") 有了这些,我希望它能打印“你好”,睡一会儿,“世界”。到

我希望创建一个小模块来实现文本滚动的功能。到目前为止,我已经尝试了一些方法,这就是我所坐的:

from time import sleep

def text_scroll(x):
    x = x.split()
    #here is where I'd like to add the sleep function
    x = " ".join(x)

print x

text_scroll("hello world.")
有了这些,我希望它能打印“你好”,睡一会儿,“世界”。到目前为止,我得到的最好结果是它没有返回任何结果,而不是实际暂停

for word in x.split():
    print word,
    time.sleep(1)

逗号阻止打印向输出添加换行符

请尝试以下代码:

from time import sleep
from sys import stdout

def text_scroll(text):
    words = text.split()
    for w in words:
        print w,
        stdout.flush()
        sleep(1)
打印结束处的逗号不添加新行“\n”。
函数的作用是:将单词刷新到屏幕上(标准输出)。

如果是python 2.7,您可以执行以下操作,这就是火山所建议的

from time import sleep

def text_scroll(x):
    for word in x.split():
        print word,
        sleep(1)

text_scroll("Hello world")
这是因为它将输入拆分为单个单词,然后打印它们,并在每个单词之间休眠。
print-word,
是用于print
word
的python 2.7,没有换行符

你的不起作用有几个原因:

def text_scroll(x):
    x = x.split()
    #here is where I'd like to add the sleep function
    x = " ".join(x)
此函数对其生成的变量不做任何处理,并且会将其损坏:

def text_scroll(x):
    x = x.split()                 # x = ["Hello", "world"]
    #here is where I'd like to add the sleep function
    x = " ".join(x)               # x = "Hello world"
它实际上对结果没有任何影响,所以它被扔掉了。但认识到这一点也很重要,因为它是一个
def
,所以它在被调用之前不会执行

当您
打印x
时,
x
尚未设置,因此它应该会给您一个
名称错误:未定义名称“x”


最后,调用函数
text\u scroll(“hello world”)
,该函数不输出任何内容,并完成。

print x
需要缩进。另外,
sleep(1)
给了您什么?您使用的是python 2.7还是python 3?如果您缺少什么,则需要从函数中返回一些内容。这适用于python 2.7,尽管您不需要
时间。
如果您像他那样导入。同样值得解释的是,为什么
打印单词,
做的就是它所做的,为什么
很重要谢谢!我的解释器不需要我在ipython中使用的stdout.flush(),而且在没有flush()调用的情况下它也不会flush,因此我添加了它。有趣的是,从控制台解释器中可以看出,没有flush它是不能工作的,但是PyCharm的控制台在没有flush的情况下工作得很好。显然PyCharm在为我表演一些魔术。