Python |避免从列表中随机选择先前的值 [英] Python | Avoid previous value from random selection from list

查看:69
本文介绍了Python |避免从列表中随机选择先前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我要我的代码执行的操作是打印出5个wrong()函数,而同一行中没有2个.当然,我不希望它靠运气. :)

Basically what I want my code to do is to print out 5 wrong() func's without there being 2 in a row of the same text. And of course i don't want it to be by luck. :)

尽管不必担心它会打印出5个wrong()的部分,但我只想确保是否至少两次使用了此功能,所以我100%确保以前的值与下一个.

Though don't worry about the part of it printing out 5 wrong()s, I just want to make sure if I use this function at least twice I am 100% sure the previous value won't be the same as the next.

例如,我要避免的事情:

For example, what i want to avoid:

Wrong!
Wrong!

这仍然可以:

Wrong!
Incorrect!
Wrong!

我的代码:

import random

def wrong():
    wrong_stats=["\n Wrong!","\n Tough Luck!","\n Better Luck Next Time!","\n Not there yet!","\n Incorrect!"]
    rand = random.choice(wrong_stats)
    rand3 = random.choice(wrong_stats)
    norep(rand,rand3,wrong_stats)

def norep(rand,rand3,wrong_stats):
    if rand == rand3:
        same = True
        while same:
            rand = random.choice(wrong_stats)
            if rand != rand3:
                print(rand)
                break

    elif rand != rand3:
        print(rand)

wrong()
wrong()
wrong()
wrong()
wrong()

推荐答案

您需要跟踪它返回的最后一个值.你可以

You'll need to keep track of the last value it returned; you could

  • 为此全局使用模块(通常在实践中比较混乱),
  • 或将其变成类(有点冗长)
  • 或在外部进行跟踪,并在每次(笨拙而繁琐)
  • use a module global for this (usually messy in practice),
  • or turn it into a class (kind of verbose),
  • or keep track externally and pass it in each time (clunky and tedious),

但是imo最好的方法是将wrong函数转换为生成器而是:这样,您可以跟踪生成器执行状态中最后一个返回的值,并在下次避免它,而不必担心任何地方的外部代码中的情况.

but imo the nicest way to do it would be to turn your wrong function into a generator instead: that way you can keep track of the last returned value in the generator execution state, and avoid it next time around, without having to worry about that in external code anywhere.

def wrong():
    wrong_stats = ["Wrong!","Tough Luck!","Better Luck Next Time!","Not there yet!","Incorrect!"]
    previous_value = None
    while True:
        value = random.choice(wrong_stats)
        if value != previous_value:
            yield value
            previous_value = value

和用法:

w = wrong()
for i in range(5):
    print(next(w))

# Tough Luck!
# Incorrect!
# Not there yet!
# Tough Luck!
# Better Luck Next Time!

您可以继续使用生成器调用next,它将生成无限数量的字符串,而无需重复先前的值.

You can keep calling next with your generator and it will produce an infinite number of strings without ever repeating the previous value.

这篇关于Python |避免从列表中随机选择先前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆