【问题标题】:Random without repetition?随机不重复?
【发布时间】:2015-06-09 15:04:38
【问题描述】:

我想编写一个程序,以随机顺序显示列表的所有元素而不重复。 在我看来,它应该可以工作,但只会重复打印这些元素。

import random

tab = []

for i in range(1, 8):
    item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"])
    if item not in tab:
        print(item)
    else:
        tab.append(item)
        continue

【问题讨论】:

标签: python random


【解决方案1】:

for 循环中不要使用random.choice,而是在此处使用random.shuffle

这样,你的列表就保证了所有元素,同时也保持了随机顺序的要求:

>>> import random
>>> tab = ["house", "word", "computer", "table", "cat", "enter", "space"]
>>> random.shuffle(tab)
>>> print tab

至于您的原始代码,这将不起作用,因为您编写的 if else 块确保不会在列表 tab 中添加任何元素。您可以通过删除 else 块来纠正它,如下所示:

>>> for i in range(1, 8):
...     item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"])
...     if item not in tab:
...         print(item)
...         tab.append(item)
... 
house
cat
space
enter

但现在您需要更改逻辑,以便随机返回相同值的运行不会影响输出数量。

【讨论】:

    【解决方案2】:

    了解 Random 库的功能。 它可以写得更简单。例如:

    import random
    
    data = ["house", "word", "computer", "table", "cat", "enter", "space"]
    x = random.sample(data, len(data))
    print(x)
    

    【讨论】:

      【解决方案3】:
      import random
      items = ["house", "word", "computer", "table", "cat", "enter", "space"]
      tab= []
      while len(tab) < len(items):
          item = random.choice(items)
          if item not in tab:
          tab.append(item)
      print(tab)
      
          
      

      【讨论】:

      • 请在这个答案中添加一些描述
      【解决方案4】:

      正如 Anshul 指出的那样,使用随机洗牌很棒:

      import random
      
      options = ["house", "word", "computer", "table", "cat", "enter", "space"]
      random.shuffle(options)
      print (options)
      

      如果您不想导入随机库,可以解决如下问题:

      options_shuffled = []
      options = ["house", "word", "computer", "table", "cat", "enter", "space"]
      while len(options) > 0:
          random_bytes = open('/dev/urandom', 'rb').read(4)
          idx = int(int.from_bytes(random_bytes, 'big') / 2 ** (8 * 4) * len(options))
          options_shuffled.append(options[idx])
          del options[idx]
      
      print (options_shuffled)
      

      【讨论】:

        猜你喜欢
        • 2011-06-19
        • 1970-01-01
        • 2011-09-04
        • 2015-11-30
        • 1970-01-01
        • 2020-05-13
        • 1970-01-01
        • 2012-07-19
        • 2010-11-16
        相关资源
        最近更新 更多