I need to get a random element from a list (that is not two of the values in the list). The following works fine:
Company dest = companies
.Where(cpy => cpy != src && cpy != plyr.PowerUpInAction.Passenger.Destination)
.OrderBy(pu => rand.Next())
.ToList()[0];
Is there a better (ie more efficient) way to do this? Converting to a list strikes me as extra work.
thanks - dave
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.
Note: If you want to generate random number based on a list, you can use this formula =INDEX($I$2:$I$7, RANDBETWEEN(1, 6)), and press Enter key.
First, we select a random index for using Random. nextInt(int bound) method. Instead of Random class, you can always use the static method Math. random()(random() method generate a number between 0 and 1) and multiply it with list size.
You could do .First()
instead of .ToList()[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With