[英]Generate list of 5 non-repeating integers
I'm new to Python and I am trying to generate a list of 4 random numbers with integers between 1 and 9. The list must contain no repeating integers.我是 Python 新手,我正在尝试生成一个包含 4 个随机数的列表,其中的整数介于 1 和 9 之间。该列表不得包含重复的整数。
The issue I am having is that the program doesn't output exactly 4 numbers everytime.我遇到的问题是该程序不会每次都输出恰好 4 个数字。 Sometimes it generates 3 numbers or 2 numbers and I can't figure out how to fix it.
有时它会生成 3 个或 2 个数字,我不知道如何解决它。
My code:我的代码:
import random
lst = []
for i in range(5):
r = random.randint(1,9)
if r not in lst: lst.append(r)
print(lst)
Is there a way to do it without the random.sample?有没有办法在没有 random.sample 的情况下做到这一点? This code is part of a larger assignment for school and my teacher doesn't want us using the random.sample or random.shuffle functions.
此代码是学校更大作业的一部分,我的老师不希望我们使用 random.sample 或 random.shuffle 函数。
Your code generates 5 random numbers, but they are not necessarily unique.您的代码生成 5 个随机数,但它们不一定是唯一的。 If a
2
is generated and you already have 2
in list
you don't append it, while you should really be generating an alternative digit that hasn't been used yet.如果生成了
2
并且list
已经有2
,则不要附加它,而实际上应该生成一个尚未使用的替代数字。
You could use a while
loop to test if you already have enough numbers:您可以使用
while
循环来测试您是否已经有足够的数字:
result = [] # best not to use list as a variable name!
while len(result) < 5:
digit = random.randint(1, 9)
if digit not in result:
result.append(digit)
but that's all more work than really needed, and could in theory take forever (as millions of repeats of the same 4 initial numbers is still considered random).但这比真正需要的工作要多,而且理论上可能需要永远(因为相同的 4 个初始数字的数百万次重复仍然被认为是随机的)。 The standard library has a better method for just this task.
标准库有一个更好的方法来完成这个任务。
Instead, you can use random.sample()
to take 5 unique numbers from a range()
object:相反,您可以使用
random.sample()
从range()
对象中获取 5 个唯一数字:
result = random.sample(range(1, 10), 5)
This is guaranteed to produce 5 values taken from the range, without duplicate digits, and it does so in 5 steps.这保证从范围中产生 5 个值,没有重复的数字,它分 5 个步骤。
Use random.sample
:使用
random.sample
:
import random
random.sample(range(1, 10), 4)
This generates a list of four random values between 1
to 9
with no duplicates.这会生成一个包含
1
到9
之间的四个随机值的列表,没有重复。
Your issue is, you're iterating 5 times, with a random range of 1-9.您的问题是,您要迭代 5 次,随机范围为 1-9。 That means you have somewhere in the neighborhood of a 50/50 chance of getting a repeat integer, which your conditional prevents from being appended to your list.
这意味着您有大约 50/50 的机会获得重复整数,您的条件会阻止将其附加到您的列表中。
This will serve you better:这将更好地为您服务:
def newRunLst():
lst = []
while len(lst) < 4:
r = random.randint(1,9)
if r not in lst: lst.append(r)
print lst
if random list needed is not too small (compared to the total list) then can如果需要的随机列表不是太小(与总列表相比),则可以
(pd.DataFrame([(i,np.random.rand()) for i in range(10)]).sort_values(by=1))[0][:5].sort_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.