user2989963
user2989963

Reputation: 11

Python randomly select an element from a 2D array and add to it

how can I randomly select an element from a 2d array and then add to it?

amount_to_add = 13
my_array = [[0,0],[0,0],[0,0]]

I want to randomly add 13 to one of the elements so it'd look like

my_array = [[0,0],[0,13],[0,0],[0,0]]

Upvotes: 0

Views: 3121

Answers (2)

user2555451
user2555451

Reputation:

This works:

>>> from random import choice, randint
>>> amount_to_add = 13
>>> my_array = [[0,0],[0,0],[0,0]]
>>> element = choice(my_array)
>>> element[randint(0, len(element)-1)] += amount_to_add
>>> my_array
[[13, 0], [0, 0], [0, 0]]
>>> my_array = [[0,0],[0,0],[0,0]]
>>> element = choice(my_array)
>>> [randint(0, len(element)-1)] += amount_to_add
>>> my_array
[[0, 0], [0, 0], [0, 13]]
>>>

It randomly chooses an element in my_array, randomly chooses an index on that element, and then adds amount_to_add to the item at that index.

Upvotes: 1

aIKid
aIKid

Reputation: 28292

import random

my_array[random.randrange(len(my_array))].append(amount_to_add)

Just that simple.

Demo:

>>> my_array = [[0],[0],[0],[0]]
>>> my_array[random.randrange(len(my_array))].append(amount_to_add)
>>> my_array[random.randrange(len(my_array))].append(amount_to_add)
>>> my_array
[[0], [0], [0, 10], [0, 10]]

Edit: Turns out i misunderstood the question. Here is how to add:

>>> my_array = [[0,0],[0,0],[0,0],[0,0]]
>>> random.choice(my_array)[random.randrange(len(choice))] += amount_to_add
>>> my_array
[[0, 10], [0, 0], [0, 0], [0, 0]]
>>> random.choice(my_array)[random.randrange(len(choice))] += amount_to_add
>>> my_array
[[0, 10], [0, 0], [0, 0], [0, 10]]

Upvotes: 2

Related Questions