我想在给定两个输入的情况下创建一个列表,并且在不能有任何重复的情况下。该列表应包含随机的数字序列。那么列表中的数字是正整数。
输入1:列表的长度(var
samples
)输入 2:列表的最大编号(var
end
)
我知道如何做到这一点,但我希望列表包含大量数字、100 万个数字或更多。我自己创建了 2 种方法来解决这个问题,它们都有自己的问题,其中slow
一个产生了MemoryError
.
方法1 MemoryError
,:
import random
def create_lst_rand_int(end, samples):
if samples > end:
print('You cannot create this list')
else:
lst = []
lst_possible_values = range(0, end)
for item in range(0, samples):
random_choice = random.choice(lst_possible_values)
lst_possible_values.remove(random_choice)
lst.append(random_choice)
return lst
print create_lst_rand_int(1000000000000, 100000000001)
方法2 slow
,:
import random
def lst_rand_int(end, samples):
lst = []
# lst cannot exist under these conditions
if samples > end:
print('List must be longer or equal to the highest value')
else:
while len(lst) < samples:
random_int = random.randint(0, end)
if not random_int in lst:
lst.append(random_int)
return lst
print lst_rand_int(1000000000000, 100000000001)
由于我的两种方法都不能很好地工作(方法 1 确实比方法 2 更好)我想知道如何创建一个更好地满足我的要求的列表。