I need to rearrange my List array, it has a non-determinable number of elements in it.
Can somebody give me example of how i do this, thanks
Because a string is an immutable type, and You can't modify the immutable objects in Python. The random. shuffle() doesn't' work with String.
Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.
To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.
List<Foo> source = ... var rnd = new Random(); var result = source.OrderBy(item => rnd.Next());
Obviously if you want real randomness instead of pseudo-random number generator you could use RNGCryptoServiceProvider instead of Random.
This is an extension method that will shuffle a List<T>
:
public static void Shuffle<T>(this IList<T> list) { int n = list.Count; Random rnd = new Random(); while (n > 1) { int k = (rnd.Next(0, n) % n); n--; T value = list[k]; list[k] = list[n]; list[n] = value; } }
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