【问题标题】:random list choice: How do I make sure the same item isn't ever repeated twice in a row, one after the other?随机列表选择:如何确保同一项目不会连续重复两次,一个接一个?
【发布时间】:2017-08-02 11:29:10
【问题描述】:
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 不会连续重复两次?以后再重复就好了,不要马上重复。

【问题讨论】:

  • random.sample(welcomes,2)这样的样本对

标签: python python-3.x list random


【解决方案1】:

使用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))

【讨论】:

  • 你可以使用循环来节省代码重复
【解决方案2】:

如果你想生成一个很长的问候流具有属性:没有连续的问候是相同的(在线演示: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))

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

if welcomes[0] == last_hello:
    welcomes[0], welcomes[1] = welcomes[1], welcomes[0]

或随机:

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

【讨论】:

    【解决方案3】:

    像其他建议的答案一样,使用random.sample 仅在您知道只需要一定数量的项目(例如2)时才有用。确保随机性和不重复的最佳方法是使用random.shuffle

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

    这很好地就地打乱列表,然后您可以开始将pop 项目从列表中移开,直到完成:

    while len(welcomes)>0:
        print("You have entered the welcome cave ----- {} -----".format(welcomes.pop())
    

    这适用于任何长度的列表,您可以使用此过程直到完成整个列表。如果您想让它永远持续下去,而不仅仅是直到列表结束,您还可以在整个过程中添加另一个循环。

    【讨论】:

      【解决方案4】:

      你可以通过命中与错过的方法来做到这一点:

      import random
      
      class RandomChoiceNoImmediateRepeat(object):
          def __init__(self, lst):
              self.lst = lst
              self.last = None
          def choice(self):
              if self.last is None:
                  self.last = random.choice(self.lst)
                  return self.last
              else:
                  nxt = random.choice(self.lst)
                  # make a new choice as long as it's equal to the last.
                  while nxt == self.last:   
                      nxt = random.choice(self.lst)
                  # Replace the last and return the choice
                  self.last = nxt
                  return nxt
      

      可以使用random.choices 和权重(需要 python-3.6)对其进行优化,但该方法应该适用于所有 python 版本:

      >>> welcomes = ["Hello","Hi","What's up","YO", "Piss off"]
      >>> gen = RandomChoiceNoImmediateRepeat(welcomes)
      >>> gen.choice()
      'YO'
      

      或者,如果您不喜欢 hit&miss,您也可以在 0 和列表长度之间绘制一个随机索引 - 2,如果它等于或高于前一个,则添加 1。这样可以确保不会发生重复,并且只需要一次调用 random 即可获得下一个选择:

      import random
      
      class RandomChoiceNoImmediateRepeat(object):
          def __init__(self, lst):
              self.lst = lst
              self.lastidx = None
      
          def choice(self):
              if self.lastidx is None:
                  nxtidx = random.randrange(0, len(self.lst))
              else:
                  nxtidx = random.randrange(0, len(self.lst)-1)
                  if nxtidx >= self.lastidx:
                      nxtidx += 1
              self.lastidx = nxtidx
              return self.lst[nxtidx]
      

      【讨论】:

        【解决方案5】:

        我的看法:我们创建了两个相同的列表。在循环中,我们从一个列表中弹出一个值,如果该列表的长度小于原始列表 - 1,我们将列表重置为其原始状态:

        import random
        
        origin = ["Hello","Hi","What's up","YO", "Piss off"]
        welcomes = origin.copy()
        
        for i in range(5):
            if len(welcomes) < len(origin) - 1:
                welcomes = origin.copy()
            random.shuffle(welcomes) # shuffle
            chosen = welcomes.pop() # pop one value
            print("You have entered the welcome cave ----- {} -----".format(chosen))
        

        例如输出 5 个循环:

        You have entered the welcome cave ----- Piss off -----
        You have entered the welcome cave ----- YO -----
        You have entered the welcome cave ----- Piss off -----
        You have entered the welcome cave ----- YO -----
        You have entered the welcome cave ----- What's up -----
        

        【讨论】:

          【解决方案6】:

          = 输出中放入[a = list.consumableList] 而不仅仅是列表

          (将括号中的小写列表替换为您的列表名称)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-09-15
            • 2015-06-30
            • 1970-01-01
            • 1970-01-01
            • 2012-10-22
            • 2010-09-23
            • 1970-01-01
            相关资源
            最近更新 更多