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 Do i Randomly Select an Item From A List?
import random
items = ["random1", "random2", "random3"]
random.choice(items)
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
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]
R: Randomly Selecting Items from a List
It seems straight-forward unless I am missing something, you have a list of foods and days, so just keep track of the available options each time you run through a person and only select from those options:
## initialize the inputs
set.seed(1)
foods <- letters[1:20]
nfoods <- sample(5, 4)
tmp <- list(unpicked = list(food = foods, days = 1:365))
## run it
tmp <- lapply(nfoods, function(x) tmp <<- f(tmp$unpicked$food, x, tmp$unpicked$days))
## summarize it
res <- sapply(seq_along(tmp), function(ii) {
x <- tmp[[ii]]
x <- sprintf('person %s: "%s" and "%s"', ii, toString(x$picked$food),
paste0(x$picked$days, collapse = '-'))
cat(x, sep = '\n')
invisible(x)
})
# person 1: "b" and "270-299"
# person 2: "s, a, k, g" and "306-336"
# person 3: "m, t, h" and "42-89"
# person 4: "j, f, q, o, l" and "129-210"
f <- function(food, n, days) {
# f(1:4, 3, 1:10)
food1 <- sample(food, n)
days1 <- split(days, cumsum(is.na(days)))
days1 <- sample(Filter(function(x) length(x) > 2, days1), 1)[[1]]
days1 <- sort(sample(sort(days1), 2))
days[do.call('seq', as.list(days1))] <- NA
list(
picked = list(food = food1, days = days1),
unpicked = list(food = setdiff(food, food1), days = days)
)
}
Related Topics
Converting an Array of Objects to an Array of Their Primitive Types
Swing's Keylistener and Multiple Keys Pressed at the Same Time
How to Fetch Fetchtype.Lazy Associations with JPA and Hibernate in a Spring Controller
Hadoop No Filesystem for Scheme: File
Persistencecontext Entitymanager Injection Nullpointerexception
Why I Can't Create an Array with Large Size
Java:Non-Static Variable Cannot Be Referenced from a Static Context Error
How to Update Path Variable Permanently from Windows Command Line
Why Can't Enum's Constructor Access Static Fields
How to Use Aop with Aspectj for Logging
Platform Independent Paths in Java
Dynamic Graphics Object Painting
Ignoring Ssl Certificate in Apache Httpclient 4.3
What Is More Efficient: System.Arraycopy or Arrays.Copyof
Where Do Java and .Net String Literals Reside
How to Add Unicode in Truetype0Font on PDFbox 2.0.0