如何在 Python 中生成不重复的随机数?
在本文中,我们将向您展示如何在 Python 中生成不重复的随机数。以下是完成此任务的方法:
使用 randint() 和 append() 函数
使用给定列表的 random.sample() 方法
使用一系列数字的 random.sample() 方法
使用 random.choices() 方法
使用 randint() 和 append() 函数 append() 函数
算法(步骤)
以下是执行所需任务所要遵循的算法/步骤 -
使用 import 关键字导入 random 模块。
创建一个空列表,即结果随机数列表。
使用 for 循环遍历循环 15 次。
使用 random 模块的 randint() 函数(返回指定范围内的随机数),在指定范围内生成一个随机数,即从 1 到 100。
使用 if 条件语句检查使用 not 和 in 运算符(Python 成员运算符)检查生成的随机数是否不在结果 randomList 中。
如果条件为 True,则使用 append() 函数(将元素添加到列表末尾)将随机数附加到结果列表中。
打印结果 list() 函数(将序列/可迭代对象转换为列表),将 上述集合转换为列表。现在列表仅包含唯一元素。
使用 sample() 函数,将包含唯一项的列表 k 值作为参数传递给它,以从列表中打印 k(此处为 4)个不重复的随机数。
示例
以下程序使用 random.sample() 函数返回 4 个不重复的随机数 −
# importing random module import random # input list inputList = [1, 2, 3, 1, 4, 3, 5, 7, 9, 8, 2, 3] # removing repeating elements from the list using the set() function resultSet=set(inputList) # converting the set into a list(now the list has only unique elements) uniqueList =list(resultSet) # printing 4 random numbers from the list which is non-repeating print("4 non-repeating random numbers from the list are:") print(random.sample(uniqueList, 4))
输出
执行时,上述程序将生成以下输出 -
4 non-repeating random numbers from the list are: [7, 2, 4, 8]
使用 random.sample() 方法对一系列数字进行采样
算法(步骤)
以下是执行所需任务需要遵循的算法/步骤 -
使用 import 关键字导入 random 模块。
使用 range() 函数获取指定范围内的数字,即此处为 1 到 100(range() 函数返回从 0 开始并以 1 递增(默认)并在给定数字之前停止的数字序列)。
使用 range() 函数获取指定范围内的数字,即此处为 1 到 100(range() 函数返回从 0 开始并以 1 递增(默认)并在给定数字之前停止的数字序列)。
使用 sample() 函数,将给定范围的数字列表、k 值作为参数传递给它,以从列表中打印 k(此处为 4)个不重复的随机数。
示例
以下程序使用 random.sample() 函数返回 4 个不重复的随机数 −
# importing random module import random # getting numbers from 0 to 100 inputNumbers =range(0,100) # printing 4 random numbers from the given range of numbers which are # non-repeating using sample() function print("4 non-repeating random numbers are:") print(random.sample(inputNumbers, 4))
输出
执行时,上述程序将生成以下输出 -
4 non-repeating random numbers are: [67, 50, 61, 47]
使用 random.choices() 方法
random 模块包含 random.choices() 方法。从列表中选择多个项目或从特定序列中选择单个项目很有用。
语法
random.choices(sequence, k)
参数
sequence(必需) - 任何序列,如列表、元组等。
k(可选) - 返回列表的长度(整数)
示例
以下程序使用 random.choices() 函数返回 4 个不重复的随机数 -
# importing random module import random # getting numbers from 0 to 100 inputNumbers =range(0,100) # printing 4 random numbers from the given range of numbers which are # non-repeating using choices() function print("4 non-repeating random numbers are:") print(random.choices(inputNumbers, k=4))
输出
执行时,上述程序将生成以下输出 -
4 non-repeating random numbers are: [71, 4, 12, 21]
Conclusion
In this tutorial, we learned how to generate non-repeating numbers in Python using four different ways. We learned how to generate non-repeating numbers that are not on the list. We learned How to determine whether an element is included in a list in order to generate non-repeating integers.