theguyty
theguyty

Reputation: 33

Python - Random frequency for changing values in a list

I have a list that contains two lists and I am looking to randomly select one of the values within both of these lists and then multiply them by 0.5

For example, I receive a list like this:

[[-0.03680804604507722, 0.022112919584121357], [0.05806232738548797, -0.004015137642131433]]

Upvotes: 1

Views: 172

Answers (2)

Paul Rooney
Paul Rooney

Reputation: 21609

You can use randint and the length of the list.

from random import randint

lst = [[-0.03680804604507722, 0.022112919584121357], [0.05806232738548797, -0.004015137642131433]]

for L in lst:
    L[randint(0, len(L) - 1)] *= 0.5

Upvotes: 1

TheF1rstPancake
TheF1rstPancake

Reputation: 2378

What it sounds like you want to do is iterate through your list of lists, and at each list, randomly select an index, multiply the value at that index by 0.5 and place it back in the list.

import random
l = [[-0.03680804604507722, 0.022112919584121357], [0.05806232738548797, -0.004015137642131433]]

# for each sub list in the list
for sub_l in l:
   # select a random integer between 0, and the number of elements in the sub list
   rand_index = random.randrange(len(sub_l))

   # and then multiply the value at that index by 0.5 
   # and store back in sub list
   sub_l[rand_index] = sub_l[rand_index] * 0.5

Upvotes: 1

Related Questions