lundi 3 juillet 2017

Randomly remove 'x' elements from a list

I'd like to randomly remove a fraction of elements from a list without changing the order of the list.

Say I had some data and I wanted to remove 1/4 of them:

data = [1,2,3,4,5,6,7,8,9,10]
n    = len(data) / 4

I'm thinking I need a loop to run through the data and delete a random element 'n' times? So something like:

for i in xrange(n):
    random = np.randint(1,len(data))
    del data[random]

My question is, is this the most 'pythonic' way of doing this? My list will be ~5000 elements long and I want to do this multiple times with different values of 'n'.

Thanks!




Aucun commentaire:

Enregistrer un commentaire