随机列表选择:如何确保同一个项目不会连续重复两次,一个接一个?

2024-04-24 23:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

import random

welcomes = ["Hello","Hi","What's up","YO", "Piss off"]

chosen = random.choice(welcomes)

print("You have entered the welcome cave ----- {} -----".format(chosen))

如何确保Hello不会在一行中重复两次?如果以后再重复也没关系,只是不要直接重复。在


Tags: importyouhellohaverandomhiwhatprint
3条回答

使用random.sample代替random.choiceFind online demo

import random

welcomes = ["Hello","Hi","What's up","YO", "Piss off"]

chosen = random.sample(welcomes,2)

for item in chosen:
  print("You have entered the welcome cave ----- {} -----".format(item))

使用random.sample和其他建议的答案一样,只有当你知道你只需要一定数量的项目时,才有用,比如2。确保随机性和无重复的最佳方法是使用random.shuffle

import random
welcomes = ["Hello","Hi","What's up","YO", "Piss off"]
random.shuffle(welcomes)

这样可以很好地将列表洗牌,然后您就可以从列表中开始pop项,直到完成:

^{pr2}$

这对任何长度的列表都有效,您可以使用此过程直到整个列表完成。如果你想让它永远运行,而不仅仅是在列表结束之前,你还可以在整个过程中添加另一个循环。在

如果您想生成一个具有以下属性的长问候语流:没有连续的问候语是相同的(联机演示:last version):

import random

def random_hello():
    welcomes = ["Hello", "Hi", "What's up", "YO", "Piss off"]
    last_hello = None
    while 1:
        random.shuffle(welcomes)
        if welcomes[0] == last_hello:
            continue
        for item in welcomes:
            yield item
        last_hello = welcomes[-1]


hellower = iter(random_hello())
for _ in range(1000):
    print(next(hellower))

或者当您担心确定性时间时,交换元素(与第一个元素):

^{pr2}$

或随机:

if welcomes[0] == last_hello:
    swap_with = random.randrange(1, len(welcomes))
    welcomes[0], welcomes[swap_with] = welcomes[swap_with], welcomes[0]

相关问题 更多 >