How to Randomly Select an Item from a List

How can I randomly select an item from a list?

Use random.choice():

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice():

import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))

secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:

import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

How to randomly pick an item in a list excluding one possiblity?

Two main strategies are possible:

Remove the exception from the list, and sample from that:

import random

def choice_excluding(lst, exception):
possible_choices = [v for v in lst if v != exception]
return random.choice(possible_choices)

Or just take a random choice from your complete list, and try again as long a you get the forbidden value (rejection sampling):

def reject_sample(lst, exception):
while True:
choice = random.choice(lst)
if choice != exception:
return choice

Both will get the same results (well, as long as same goes for random...):

lst = [2, 4, 5, 7, 9, 34, 54]
choice_excluding(lst, 7)
# 9
reject_sample(lst, 7)
# 54

Depending on the size of your list, one may be faster than the other. Try and see!

How to choose a random element from a list and then find its index in the list?

You can use list.index():

x.index(y)

This will return the first index in the list where it finds a match. However, this will not return the correct index if you have duplicates in your list.


A better way to handle this, in the case you have duplicates would be to randomise the index instead of the value. As you will always store the correct index you're referencing and not the first occurance.

y = random.randint(0, len(x))
#3

x[y]

#Sophia

How Do i Randomly Select an Item From A List?

import random
items = ["random1", "random2", "random3"]
random.choice(items)

How to randomly select two elements of a python list?

You can use random.sample Try this:

import random
mylist = ['a','b','c','d']

print(random.sample(mylist, 2))

How to randomly pick element from an array with different probabilities in C++

You are looking for std::discrete_distribution. Forget about rand().

#include <random>
#include <vector>

struct Point {};

int main() {
std::mt19937 gen(std::random_device{}());

std::vector<double> chances{1.0, 2.0, 3.0};
// Initialize to same length.
std::vector<Point> points(chances.size());
// size_t is suitable for indexing.
std::discrete_distribution<std::size_t> d{chances.begin(), chances.end()};

auto sampled_value = points[d(gen)];
}

Conveniently for you, the weights do not have to sum to 1.

Randomly select an element from a list, but the lower an element is, the more chance it has to be selected

New in Python 3.6. For the previous Python version see here.

You can use the weights or cum_weights parameter in random.choices() to select according to the relative weights.

Since you want a higher change of selection for elements present at higher index, you can make your weights index based.

weights = [i for i in range(1, len(links) + 1)]

Internally, the relative weights(weights) are converted to cumulative weights(cum_weights) before making selections.

random.choices(links, weights=weights)

Note: If a weights sequence is supplied, it must be of the same length as the sample sequence.

Select item from a list like random.choice() does, but not randomly

You have a few options for this.

List indexing:

worker = workers[0]
del workers[0]

.pop():

worker = workers.pop(0)
# pop removes item from list and assigns to worker

next():

#convert list to iterator
w_iter = iter(workers)
# anytime you need the next worker, call the following line
worker = next(workers)

Also consider looping through workers:

for worker in workers:
do_something()

Maybe the easiest for you:

for i, row in routes.iterrows():
worker = workers[i]


Related Topics



Leave a reply



Submit