Python random element in array

How to get a random element from an array in python

secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:,Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.,If you also need the index, use random.randrange,As of Python 3.6 you can use the secrets module, which is preferable to the random module for cryptography or security uses.

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)) 

Answer by Michael Cunningham

Selecting a Random Element From Python List,Selecting More Than One Random Element From Python List,Selecting Random n Elements with No Repetition,The most intuitive and natural approach to solve this problem is to generate a random number that acts as an index to access an element from the list.

We’ll want random index in the range of 0 to len(list)-1 , to get a random index of an element in the list:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] random_index = random.randint(0,len(letters)-1) print(letters[random_index]) 

Running this code multiple times yields us:

random.randrange(a) is another method which returns a random number n such that 0

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] random_index = random.randrange(len(letters)) print(letters[random_index]) 

Running this code multiple times will produce something along the lines of:

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

Running this multiple times results in:

The first method that we can make use of to select more than one element at random is random.sample() . It produces a sample, based on how many samples we’d like to observe:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.sample(letters, 3)) 
print(random.sample(letters, len(letters))) 

Similar to the previous function, random.choices() returns a list of randomly selected elements from a given iterable. Though, it doesn’t keep track of the selected elements, so you can get duplicate elements as well:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.choices(letters, k=3)) 

This returns something along the lines of:

print(random.choices(letters, k = len(letters))) 

It can return something like:

Читайте также:  Qr code php base64

We’ll save the result in a new list, and if there’s not enough elements to fit a final collection, it’ll simply be unfinished:

import random def select_random_Ns(lst, n): random.shuffle(lst) result = [] for i in range(0, len(lst), n): result.append(lst[i:i + n]) return result lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(select_random_Ns(lst, 2)) 

This results in a list of random pairs, without repetition:

Answer by Clarissa Bravo

import random #1.A single element random.choice(list) #2.Multiple elements with replacement random.choices(list, k = 4) #3.Multiple elements without replacement random.sample(list, 4)

Answer by Hadlee Gibbs

The random values are useful in data-related fields like machine learning, statistics and probability. The numpy.random.choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python.,Randomly choose values from the array created,Check if element exists in list in Python,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Answer by Melani Patrick

To get random elements from sequence objects such as lists, tuples, strings in Python, use choice(), sample(), choices() of the random module.,random.choices() returns multiple random elements from the list with replacement.,random.sample() returns multiple random elements from the list without replacement.,choice() returns one random element, and sample() and choices() return a list of multiple random elements. sample() is used for random sampling without replacement, and choices() is used for random sampling with replacement.

import random l = [0, 1, 2, 3, 4] print(random.choice(l)) # 1 

Answer by Gia Carpenter

Randomly select elements of a 1D array using choice(),To do weighted random sampling, it is possible to define for each element the probability to be selected:,Examples of how to randomly select elements of an array with numpy in python:,Here for example the elements 0,1,8 or 9 will have a lower probability to be selected:

Читайте также:  Javascript replace all in html

Lets create a simple 1D array with 10 elements:

>>> import numpy as np >>> data = np.arange(10) >>> data array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

To select randomly n elements, a solution is to use choice(). Example of how to select randomly 4 elements from the array data:

>>> np.random.choice(data,4) array([9, 6, 2, 9]) 

Another example, with n = 5

>>> for i in range(10): . np.random.choice(data,5) . array([3, 4, 0, 8, 4]) array([3, 0, 0, 3, 6]) array([5, 1, 2, 0, 9]) array([5, 8, 6, 0, 1]) array([4, 0, 9, 4, 2]) array([9, 6, 3, 9, 9]) array([9, 5, 1, 2, 7]) array([9, 7, 6, 4, 5]) array([6, 8, 5, 5, 9]) array([8, 9, 5, 5, 6]) 

To do random sampling without remplacement, just add the option «replace = False»:

>>> for i in range(10): . np.random.choice(data,5,replace=False) . array([9, 7, 4, 0, 6]) array([0, 9, 2, 4, 6]) array([2, 6, 5, 0, 9]) array([0, 3, 5, 7, 9]) array([0, 5, 9, 6, 7]) array([5, 0, 9, 6, 3]) array([7, 2, 6, 9, 1]) array([7, 6, 5, 8, 4]) array([6, 8, 5, 7, 4]) array([0, 1, 2, 3, 5]) 

To do weighted random sampling, it is possible to define for each element the probability to be selected:

>>> p = [0.05, 0.05, 0.1, 0.125, 0.175, 0.175, 0.125, 0.1, 0.05, 0.05] 

Note: the sum must be equal to 1:

Here for example the elements 0,1,8 or 9 will have a lower probability to be selected:

>>> for idx,p in enumerate(p): . print(p,data[idx]) . 0.05 0 0.05 1 0.1 2 0.125 3 0.175 4 0.175 5 0.125 6 0.1 7 0.05 8 0.05 9 
>>> for i in range(10): . np.random.choice(data,5,replace=False,p=p) . array([7, 5, 0, 2, 3]) array([9, 2, 3, 5, 7]) array([2, 5, 3, 7, 4]) array([7, 2, 9, 4, 5]) array([1, 4, 6, 3, 2]) array([4, 5, 3, 7, 1]) array([2, 7, 4, 6, 3]) array([6, 5, 0, 1, 8]) array([4, 0, 5, 9, 6]) array([8, 9, 3, 4, 6]) 

Lets consider the following 2D array:

>>> data = np.arange(80).reshape((8, 10)) >>> data array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74, 75, 76, 77, 78, 79]]) 

The function choice() takes only 1D array as an input, however a solution is to use ravel() to transform the 2D array to a 1D array, example:

>>> np.random.choice( data.ravel(),10,replace=False) array([64, 35, 53, 14, 48, 29, 74, 21, 62, 41]) 

Answer by Marisol Barton

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.,Functions for integers,Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.,The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

 x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha 

Answer by Elijah Webb

Example 1: how to randomly choose from a list python

Example 2: choose random index from list python

import random # Don't forget to install it first with pip install random ahahfunny = ['ahah ', 'copy-', 'paste ', 'stack overflow',' go ', 'brrr'] # the biggest index in this list above is 5 (0 being 1 in programming) print(ahahfunny[random.randint(0, 5)] # I like this way, print(random.choice(ahahfunny)) # But this way is WAY thiccer. 

Источник

Оцените статью