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

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

问题描述

我尝试使用 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天全站免登陆