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. Heres 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 arguments as (0,0) which is 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 too..
Thanks
Aucun commentaire:
Enregistrer un commentaire