I have a python dictionary as follows:
{'APPLE_PROVIDERS' : ["some", "provider","can","be", "null"],
....
}
What i want to do is get a random sublist from the list (which is a value) of a key. Not just one element, but a totally random sublist. Here is what I tried:
a_list = a_dict.get('APPLE_PROVIDERS', "")
for item in a_list[randrange(0,len(a_list)) : randrange(0,len(a_list))]:
...do something..
This thing has two problems :
If the list is empty, or if the dict lookup fails, the program fails since randrange has (0,0) as arguments, which results in an error
Many times both randrange() calls generate the same number, especially when the list is small. This returns an empty list. For example a_list[5:5]
So what is the best way to get a random sublist with above cases handled ? Also, I do not care about the ordering. Anything works. I just want a totally random sublist of either 0,1... till len(a_list) elements each time the for loop starts.
If the list can be changed in some other data structure which can hold similar elements, that works for me too.
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.
To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.
The simplest way to use Python to select a single random element from a list in Python is to use the random. choice() function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.
In order to generate random strings in Python, we use the string and random modules. The string module contains Ascii string constants in various text cases, digits, etc. The random module on the other hand is used to generate pseudo-random values.
Sample it.
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['some', 'can', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['can', 'null', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['null', 'some', 'provider']
>>> from random import randint
>>> left = randint(0, len(L))
>>> right = randint(left, len(L))
>>> L[left:right]
['null']
if you don't want the possiblity of empty lists
>>> left = randint(0, len(L) - 1)
>>> right = randint(left + 1, len(L))
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