简体   繁体   English

从函数内的列表返回非重复的随机结果

[英]Return a non-repeating, random result from a list inside a function

I am writing a Python program that responds to request and vocalizes a response back to the user. 我正在编写一个Python程序,该程序可以响应请求并向用户发出响应。 Below is a sample of two functions. 下面是两个函数的示例。 How can I do this without using a global variable and still get back a non-repeating, random response? 如何在不使用全局变量的情况下执行此操作,并且仍然返回非重复的随机响应?

# stores prior response

website_result = 'first_response.wav'

def launch_website():

    # if service is offline return with default msg otherwise launch service

    if is_connected() == 'FALSE':
       arg = 'this_service_is_offline.wav'
       return arg
    else:
       site = 'http://www.somesite.com'
       launch_it(site)

    return launch_website_response()

def launch_website_response():

    # using the global variable inside function

    global website_result

    # possible responses

    RESPONSES = ['first_response.wav', 'second_response.wav', 'third_response.wav']

    # ensures a non-repeating response

    tmp = random.choice(RESPONSES)
    while website_result == tmp:
       tmp =  random.choice(RESPONSES)

    website_result = tmp
    return website_result

Your website_result variable indicates that you to have some sort of persistent state. 您的website_result变量表示您具有某种持久状态。 Maybe you could consider storing it in a text file and access it everytime you need it and change it afterward (this works if you don't have to do too many calls to it, otherwise you will get in I/O limitations). 也许您可以考虑将其存储在文本文件中,并在每次需要时进行访问,然后进行更改(如果您不必对其进行太多调用,则可以使用此方法,否则会遇到I / O限制)。

I don't know about the specifics of your application, but it might happen that you could also make your two functions take website_result as an argument as suggested by @JGut. 我不知道您的应用程序的详细信息,但是可能会发生,您还可以使两个函数都将website_result作为@JGut建议的参数。

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

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