简单的bootstrap替换列表

时间:2014-02-05 13:36:57

标签: python random

我正在尝试执行一个简单的引导过程,将替换应用于如下格式的列表:

a = [[0.2,0.5,0.4,0.8], [0.3,0.7,0.1,0.6], [0.3,1.2,1.0,0.6], ....]

即:a是由N子列表组成的列表,每个子列表具有相同数量的浮点数(在这种情况下为4)

为了从a中选择随机元素(即:子列表)并替换以执行引导过程,我可以这样做:

import random

bts_a = []
for elem in a:
    r = random.randint(0,len(a))
    bts_a.append(a[r])

是否有更简洁和/或更快的方法来实现这一目标?我特别不喜欢初始化一个空列表(即:bts_a=[]),它对我来说感觉非常恐怖。

3 个答案:

答案 0 :(得分:3)

您可以使用random.choice和列表理解或地图:

a = [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]

>>> [random.choice(e) for e in a]
[0.5, 0.6, 0.6]
>>> [random.choice(e) for e in a]
[0.4, 0.3, 1.2]

>>> map(random.choice, a)
[0.5, 0.1, 1.0]
>>> map(random.choice, a)
[0.8, 0.3, 0.3]

从a:

中选择随机子列表
>>> random.choice(a)
[0.3, 0.7, 0.1, 0.6]
>>> random.choice(a)
[0.2, 0.5, 0.4, 0.8]

bts_a = [random.choice(a) for _ in a]
>>> bts_a
[[0.3, 1.2, 1.0, 0.6], [0.2, 0.5, 0.4, 0.8], [0.3, 1.2, 1.0, 0.6]]

答案 1 :(得分:2)

这将使用random

为您提供随机子列表
>>> from random import choice
>>> a = [[0.2,0.5,0.4,0.8], [0.3,0.7,0.1,0.6], [0.3,1.2,1.0,0.6]]
>>> print choice(a)
[0.3, 1.2, 1.0, 0.6]
>>>

 >>> print a[int(random()*len(a))]
 [0.3, 1.2, 1.0, 0.6]
 >>> a
 [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]
 >>> from random import random
 >>> print a[int(random()*len(a))]
 [0.2, 0.5, 0.4, 0.8]
 >>> print a[int(random()*len(a))]
 [0.3, 0.7, 0.1, 0.6]
 >>>

答案 2 :(得分:0)

我认为你要找的是random.shuffle

random.shuffle(a)

请注意,它会内联更改列表。如果你想要一个不同的列表。您需要创建一个副本:

bts = a[:]
random.shuffle(bts)

示例:

>>> a = [[0.2, 0.5, 0.4, 0.8], [0.3, 0.7, 0.1, 0.6], [0.3, 1.2, 1.0, 0.6]]
>>> import random
>>> random.shuffle(a)
>>> a
[[0.3, 0.7, 0.1, 0.6], [0.2, 0.5, 0.4, 0.8], [0.3, 1.2, 1.0, 0.6]]