Retrieving random subscriptions from a list in Python

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 the value) of the key. Not only one item, but also a completely 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 problem has two problems:

  • If the list is empty or if the search by query is not performed, the program crashes because randrange has (0,0) as arguments, which leads to an error

  • In many cases, randrange () calls generate the same number, especially if 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 the cases described above? In addition, I do not care about the order. Everything works. I just want a completely random subscript from 0.1 ... to len (a_list) elements every time a for loop starts.

If the list can be changed in another data structure that may contain similar elements, this also works for me.

+6
source share
4 answers

Choose 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'] 
+12
source
 >>> from random import randint >>> left = randint(0, len(L)) >>> right = randint(left, len(L)) >>> L[left:right] ['null'] 

if you do not want the possibility of empty lists

 >>> left = randint(0, len(L) - 1) >>> right = randint(left + 1, len(L)) 
+1
source

Ignacio's answer is great. If you want to change your code minimally, you can do this:

 a_list = a_dict.get('APPLE_PROVIDERS', "") if len(a_list) > 1: index1 = randrange(0,len(a_list)-1) index2 = randrange(index1+1,len(a_list)) for item in a_list[index1:index2]: pass #do stuff 

Here I do two things: 1) I check if a_list has more than one element, and 2) I generate indexes using randrange, but in such a way that the second is guaranteed to be larger than the first.

0
source

So, if you want the empty list to be returned, if you got the empty list, here is an example solution:

 from random import shuffle def get_random_sublist(the_dict, key, number): l = the_dict.get(key, []) shuffle(l) return l[:number] 

So, I would use random.shuffle . This allows me to avoid the question of suggesting more than the actual list that we get.

 >>> DICT = {'a' : "1 2 3 4 5".split(), 'b': [], 'c': [1]} >>> get_random_sublist(DICT, 'a', 3) ['4', '1', '2'] >>> get_random_sublist(DICT, 'b', 10) [] 
0
source

All Articles