10

我需要从具有固定大小的集合中随机均匀地采样一个数字,进行一些计算,然后将新数字放回集合中。(需要的样本数量非常大)

我尝试将数字存储在列表中并使用 random.choice() 选择一个元素,将其删除,然后附加新元素。但这太慢了!

我正在考虑将数字存储在一个 numpy 数组中,对索引列表进行采样,并为每个索引执行计算。

  • 有没有更快的方法来完成这个过程?
4

3 回答 3

7

Python 列表在内部实现为数组(如 Java ArrayList、C++std::vector等),因此从中间删除元素相对较慢:所有后续元素都必须重新索引。(有关更多信息,请参阅http://www.laurentluce.com/posts/python-list-implementation/。)由于元素的顺序似乎与您无关,我建议您只使用random.randint(0, len(L) - 1)选择一个 index i,然后用于L[i] = calculation(L[i])更新第ith 个元素。

于 2011-10-19T00:42:55.883 回答
4

我需要从具有固定大小的集合中随机均匀地采样一个数字,进行一些计算,然后将新数字放回集合中。

s = list(someset)           # store the set as a list
while 1:
    i = randrange(len(s))   # choose a random element
    x = s[i]
    y = your_calculation(x) # do some calculation
    s[i] = y                # put the new number back into the set
于 2011-10-19T05:44:21.977 回答
2

random .sample( a set or list or Numpy array, Nsample ) 非常快,但我不清楚你是否想要这样的东西:

import random

Setsize = 10000
Samplesize = 100
Max = 1 << 20
bigset = set( random.sample( xrange(Max), Setsize ))  # initial subset of 0 .. Max

def calc( aset ):
    return set( x + 1 for x in aset )  # << your code here

    # sample, calc a new subset of bigset, add it --
for iter in range(3):
    asample = random.sample( bigset, Samplesize )
    newset = calc( asample )  # new subset of 0 .. Max
    bigset |= newset

您可以使用 Numpy 数组或bitarray 代替set,但我希望 calc() 中的时间占主导地位。

您的 Setsize 和 Samplesize 大致是多少?

于 2011-10-21T09:47:45.840 回答