Simple bootstrap with replacement of list

python, random

Solution

You can use random.choice and list comprehension or map:

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]

to choose random sublist from 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]]

Problem

I'm attempting to perform a simple bootstrap process with replacement applied to a list formatted like so: ``` 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], ....] ``` That is: `a` is a list made of `N` sublists each with the same number of floats (4 in this case) In order to choose random elements (ie: sub-lists) from `a` with replacement to perform the bootstrap process I can do: ``` import random bts_a = [] for elem in a: r = random.randint(0,len(a)) bts_a.append(a[r]) ``` Is there a more succinct and/or faster way to accomplish this? I particulary dislike having to initialize an empty list (ie: `bts_a=[]`), it feels very non-pythonic to me.

Original source