修复随着时间的推移返回重复项的函数? [英] Fix a function returning duplicates over time?

查看:49
本文介绍了修复随着时间的推移返回重复项的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个返回 4 位字符串的函数.问题是,当我运行该函数 500 次或更多时,它开始返回重复项.如何避免这种情况?

I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?

我的功能:

import random
def CreatePass():
    Num = str(random.randint(1000, 9999)
    return Num

推荐答案

@Martijn 的解决方案就足够了,因为您只需要存储和洗牌 9000 个数字.如果您想要更大范围内的数字并且您知道(大约)您需要多少个数字,那么有一个更好的方法:函数 random.sample 将为您提供所需范围内的数字而无需重复.例如,要获得 500 个不同的六位数,您可以使用:

@Martijn's solution is enough since you only need to store and shuffle 9000 numbers. If you want numbers from a bigger range and you know (approximately) how many numbers you'll need, there's a better way: The function random.sample will give you numbers in the desired range without repetition. For example, to get 500 distinct six-digit numbers you'd use:

selected = random.sample(xrange(100000, 1000000), 500)

这篇关于修复随着时间的推移返回重复项的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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