1

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]]
1
  • I have taken a look at using random choice but I also want to put the value back into the list at the same index value. Commented Nov 9, 2016 at 3:48

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.