如何创建无重复的随机数列表? [英] How do I create a list of random numbers without duplicates?

查看:57
本文介绍了如何创建无重复的随机数列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用random.randint(0, 100),但是一些数字相同.是否有一种方法/模块来创建唯一的随机数列表?

I tried using random.randint(0, 100), but some numbers were the same. Is there a method/module to create a list unique random numbers?

注意:以下代码是基于答案的,并且已在发布答案后添加.这不是问题的一部分.是解决方案.

Note: The following code is based on an answer and has been added after the answer was posted. It is not a part of the question; it is the solution.

def getScores():
    # open files to read and write
    f1 = open("page.txt", "r");
    p1 = open("pgRes.txt", "a");

    gScores = [];
    bScores = [];
    yScores = [];

    # run 50 tests of 40 random queries to implement "bootstrapping" method 
    for i in range(50):
        # get 40 random queries from the 50
        lines = random.sample(f1.readlines(), 40);

推荐答案

这将返回从0到99范围内选择的10个数字的列表,不重复.

This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.

import random
random.sample(range(100), 10)

参考您的特定代码示例,您可能想从文件一次中读取所有行,然后从内存中的已保存列表中选择随机行.例如:

With reference to your specific code example, you probably want to read all the lines from the file once and then select random lines from the saved list in memory. For example:

all_lines = f1.readlines()
for i in range(50):
    lines = random.sample(all_lines, 40)

这样,您只需要在循环之前实际从文件中读取一次即可.与返回文件开头并为每次循环迭代再次调用f1.readlines()相比,这样做更有效.

This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call f1.readlines() again for each loop iteration.

这篇关于如何创建无重复的随机数列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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