我的问题如下,我目前正在处理生成的长度为m的列表。然而,该列表应该是以n作为最终长度参数的算法的结果。m总是比n大得多。目前我正在运行一个while循环,其中m是len(list)的结果。
from numpy import random as rnd
m = 400000
n = 3000
list = range(0, m)
while len(list) > n:
rmi = rnd.randint(0, len(list))
del list[rmi]
print('%s/%s' %(len(list), n))
这种方法当然有效,但运行时间非常长。有没有一种更高效、更省时的方法从我的列表中删除m-n个随机条目?删除的条目必须是随机的,否则生成的列表将不再代表它应该是什么。
稍后在我的代码中,我有两个大小为n的数组,需要将其缩短为大小b,这里需要注意的是,两个列表都需要随机删除元素,但删除的元素也必须共享相同的索引。即:
from numpy import random as rnd
n = 3000
b = 500
list1 = range(0, n)
list2 = rnd.sample(xrange(10000), n)
while len(list1) > b:
rmi = rnd.randint(0, len(list1))
del list1[rmi]
del list2[rmi]
print('%s/%s' %(len(list1), b)