简体   繁体   English

生成随机列表并终止它

[英]Generating a random list and termination of it

I made the following code which generates a random letter from list l every 3 seconds. 我编写了以下代码,每3秒从列表l生成一个随机字母。 The first part of my question is how do I terminate this process after 1 minute? 我的问题的第一部分是如何在1分钟后终止此过程?

import threading
import random
x = []
def printit():
    threading.Timer(3.0, printit).start()
    l = ['a', 'b', 'c', 'd']
    secure_random = random.SystemRandom()
    print x.append(secure_random.choice(l))

printit()

moreover I want to make another list from those randomly chosen letters and call it x the code above does the job, there is a little problem: when I turn the code it starts printing None, and when I interrupt and print x it gives the list of letters and keeps printing None after that, this is because I don't know how to terminate the process after one minute. 此外,我想从那些随机选择的字母中创建另一个列表,并将其命名为x上面的代码可以完成此工作,这有一个小问题:当我打开代码时,它开始打印None,当我打断并打印x它给出了列表字母并继续打印无,这是因为我在一分钟后不知道如何终止该过程。

You certainly shouldn't use threads for something like this. 您当然不应该对此类使用线程。

Instead, just 相反,只是

import time
import random

start_time = time.time()
rng = random.SystemRandom()

while time.time() - start_time < 60:  # End after a minute
    print(rng.choice('abcd'))
    time.sleep(3)

Try this code if you still want to use threading: 如果您仍然想使用线程,请尝试以下代码:

import threading
import random
import time

x = []
start_time = time.time()


def printit():
    current_time = time.time()
    print(current_time - start_time)
    if current_time - start_time > 60.0:
        return
    threading.Timer(3.0, printit).start()
    l = ['a', 'b', 'c', 'd']
    secure_random = random.SystemRandom()
    x.append(secure_random.choice(l))

    print(x)

printit()

I tested this code in Python 3.6 you may want to change the print() to print to make it work in Python 2 我在Python 3.6中测试了此代码,您可能需要更改print()才能使其在Python 2中工作

if I did not understand your question wrong, adding 如果我不明白您的问题是错误的,请添加

if x.length is 20:
     threading.Timer(3.0, printit).cancel()

at the end of your function may help 在功能结束时可能会有所帮助

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

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