我想创建一个给定两个输入的列表,并且条件是不能有任何重复项。该列表应包含随机数字序列。那么列表中的数字都是正整数。
输入1:列表的长度(var
samples
)输入2:列表的最高数(var
end
)
我知道如何执行此操作,但我希望列表包含大量数字、100 万个数字或更多。
我自己创建了 2 种方法来解决这个问题,它们都有自己的问题,一个是 slow
,另一个产生 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)
方法二,慢
:
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 效果更好),我想知道如何创建一个更好地满足我要求的列表。
最佳答案
尝试文档中给出的解决方案:
http://docs.python.org/2/library/random.html#random.sample
To choose a sample from a range of integers, use an xrange() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60).
或者,在您的情况下,random.sample(xrange(0,1000000000000), 100000000001)
这仍然是一个巨大的数据结构,可能适合也可能不适合您的内存。在我的系统上:
>>> sys.getsizeof(1)
24
因此 100000000001 个样本将需要 2400000000024 字节,或大约 2 TB。我建议您找到一种方法来处理较少数量的样本。
关于python - 创建一长串随机值,没有重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19825071/