How to access random item in list?
Create an instance of
Random
class somewhere. Note that it's pretty important not to create a new instance each time you need a random number. You should reuse the old instance to achieve uniformity in the generated numbers. You can have astatic
field somewhere (be careful about thread safety issues):static Random rnd = new Random();
Ask the
Random
instance to give you a random number with the maximum of the number of items in theArrayList
:int r = rnd.Next(list.Count);
Display the string:
MessageBox.Show((string)list[r]);
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 get random item from a list in python3 without any module
Random and pseudorandom number generators will ultimately rely on some kind of module, if only to get a seed needed to produce pseudorandom numbers. One common example of a seed is time.time
found in the time
module, though it's not necessarily a good one. The only way without a module is to choose a fixed seed, but then only a fixed sequence of numbers is possible.
Besides the seed, there is the algorithm. One popular choice is the linear congruential generator (LCG). This algorithm is appropriate for learning purposes; however, LCGs are far from perfect and should not be used in security applications or serious simulations. See this answer: How to sync a PRNG between C#/Unity and Python?
There are two more things involved in the solution: generating a uniform random integer, and choosing a uniform random item from a list.
- Generating a uniform random integer in [0, n); that is, building
RNDINTEXC(n)
. For that, see Melissa O'Neill's page. Or if you have pseudorandom or random bits, see this question. - Choosing a uniform random item from a list, doing
list[RNDINTEXC(len(list))]
.
How do I get a random item in a nested list in a dictionary?
To be clear you are assigning one value to each key. The value is a list that contains two things, "cost" and "value".
s1 = random.choice(list(shop.keys())
randomly selects a key from your dictionary, shop
. To retrieve the value associated with the key you can use s1_cost, s1_value = shop[s1]
or s1_cost, s1_value = shop.get(s1)
.
To retrieve a random item from the list you can use random.choice(shop[s1])
.
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 to find a random item from a C# list that has a specific value?
Short answer: No, you have to iterate the list.
Long answer: The probability to pick a certain item depends on the amount of items that match your criteria. Therefore, you have to scan the entire list.
What I would suggest to do is to get all matching items into a list and then take a random index. I find that more readable and less confusing than sorting by a random number.
public Category CatByName(string nm)
{
string name = nm.ToUpper();
var matching = Categories.Where(x => x.CategoryName.Contains(name)).ToList();
if (matching.Count == 0)
{
return null;
}
Random rnd = new Random();
return matching[rnd.Next(matching.Count)];
}
Related Topics
How to Round a Number to Two Decimal Places in C#
Remove Element of a Regular Array
How to Rethrow an Exception in C#
Are String.Equals() and == Operator Really Same
How to Dynamically Create Generic C# Object Using Reflection
A Potentially Dangerous Request.Path Value Was Detected from the Client (*)
Enum Tostring With User Friendly Strings
Replace Line Breaks in a String C#
Why and How to Avoid Event Handler Memory Leaks
Convert a Bitmap into a Byte Array
Raw SQL Query Without Dbset - Entity Framework Core
How to Reflect Over the Members of Dynamic Object
Conditionally Change CSS Class in Razor View
Why Doesn't C# Allow Static Methods to Implement an Interface