【问题标题】:How to get random item from a list in python3 without any module如何在没有任何模块的情况下从python3中的列表中获取随机项
【发布时间】:2020-12-30 15:39:57
【问题描述】:

我正在使用 Python 3.9 并且有一个列表 list1 = ['a', 'b', 'c', 'd'] 我想在不使用任何模块的情况下从列表中获取一个随机项目,例如 Python 中有一个模块 random 和一个函数 random.choice(list1) 我可以使用它,但是是否有另一种方法可以在不使用任何模块的情况下从 Python 列表中获取随机项?

【问题讨论】:

  • 使用random有什么问题?它是python的内置部分。
  • 是的,有办法,通过重新实现random 模块的功能。
  • 你问这个问题是为了学习吗?

标签: python python-3.x random


【解决方案1】:

随机和伪随机生成器最终将依赖于某种模块,即使只是为了获得生成伪随机数所需的种子。种子的一个常见示例是在 time 模块中找到的 time.time,尽管它不一定是好的。没有模块的唯一方法是选择一个固定的种子,但只有固定的数字序列是可能的。

除了种子,还有算法。一种流行的选择是线性同余生成器 (LCG)。该算法适用于学习目的;然而,LCG 远非完美,不应该用于安全应用或严肃的模拟。看到这个答案:How to sync a PRNG between C#/Unity and Python?

解决方案中还涉及两件事:生成一个随机整数,以及从列表中选择一个随机项。

  • 在 [0, n) 中生成一个随机整数;即构建RNDINTEXC(n)。为此,请参阅Melissa O'Neill's page
  • 从列表中随机选择一项,执行list[RNDINTEXC(len(list))]

【讨论】:

    【解决方案2】:

    如果不想使用random模块,可以使用time模块生成伪随机整数。

    import time
    
    def get_random_number(upper_limit):
        _timestamp = time.time()
        _timestamp = int(_timestamp*1000000)
        return _timestamp % upper_limit
    
    def get_item_from_list(_list):
        choice = get_random_number(len(_list))
        assert choice < len(_list), "Index should be less than length of list"
        return _list[choice]
    
    print(get_item_from_list([10, 20, 13, 24, "ABS", "DEF"]))
    
    

    您可以使用它从列表中生成随机项目。

    【讨论】:

    • "不使用任何模块" -- "你可以使用时间模块"
    【解决方案3】:

    除非您想创建自己的函数
    方法 1

    import random
    import math
    
    variable = yourarray[math.floor(random.random()*len(yourarray))]
    print(variable)
    

    方法二

    import random
    import math
    
    def shuffle(array): 
            currentIndex = len(array);
            temporaryValue= 0;
            randomIndex = 0;
          
            while (0 != currentIndex): 
                randomIndex = math.floor(random.random() * currentIndex);
                currentIndex -= 1;
          
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            
          
            return array
    yourarray = shuffle(yourarray)
    print(yourarray[0])
    

    【讨论】:

      【解决方案4】:

      这样的?假设您的列表仅包含 str

      list1 = ['a', 'b', 'c', 'd']
      
      def pick_random(array):
          return(list(set(list1))[0])
      
      print(pick_random(list1))
      

      【讨论】:

      • 问题 - 尝试运行几次,但总是给出相同的结果? (在 Python 3.8 中)
      猜你喜欢
      • 2015-10-30
      • 1970-01-01
      • 2020-09-28
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2022-01-18
      相关资源
      最近更新 更多