How do I select a random object from a list of objects?
Question:
I have a list of 10 x 10, with objects like this:
self.taula = [[casella() for i in range(10)] for j in range(10)]
How do I select a random object from this list?
I’ve been trying but of course I don’t have any integer to use as an index, I’m pretty new to coding so I might be doing something wrong.
Answers:
Assuming you want to select a random single element, you can use random.choice
twice: first to select a list within the list of lists at random, then to randomly choose from that list.
import random
rand = random.choice(random.choice(self.taula))
Note this works well when the nested lists are of equal length as each individual element has an equal likelihood of being randomly selected. However, if they are uneven, as in the below example, it does affect the randomness of the selection.
[
[1, 2, 3],
[4, 5, 6, 7, 8, 9, 10],
[0]
]
0
has a 1-in-3 chance of being picked, but 10
has a 1-in-21 chance of being picked.
To address this, you can flatten the list, and then choose from that.
flat = [y for x in self.taula for y in x]
random.choice(flat)
I have a list of 10 x 10, with objects like this:
self.taula = [[casella() for i in range(10)] for j in range(10)]
How do I select a random object from this list?
I’ve been trying but of course I don’t have any integer to use as an index, I’m pretty new to coding so I might be doing something wrong.
Assuming you want to select a random single element, you can use random.choice
twice: first to select a list within the list of lists at random, then to randomly choose from that list.
import random
rand = random.choice(random.choice(self.taula))
Note this works well when the nested lists are of equal length as each individual element has an equal likelihood of being randomly selected. However, if they are uneven, as in the below example, it does affect the randomness of the selection.
[
[1, 2, 3],
[4, 5, 6, 7, 8, 9, 10],
[0]
]
0
has a 1-in-3 chance of being picked, but 10
has a 1-in-21 chance of being picked.
To address this, you can flatten the list, and then choose from that.
flat = [y for x in self.taula for y in x]
random.choice(flat)