Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created July 10, 2013 23:00
Show Gist options
  • Save mortymacs/5970979 to your computer and use it in GitHub Desktop.
Save mortymacs/5970979 to your computer and use it in GitHub Desktop.
random_ext is a extra class for python random class. This class has shuffle_child.
#!/usr/bin/env python
import random
class random_ext():
@staticmethod
def shuffle_child(var,key,make=None):
'''
Shuffle child index
'''
fields = list()
for i in var:
try:
fields.append({key:i[key]})
except:
if make is not None:
fields.append({key:make})
random.shuffle(fields)
for i in var:
try:
if i[key] != None:
value = random.choice(fields)
i[key] = value[key]
fields.remove(value)
except:
if make is not None:
value = random.choice(fields)
i[key] = value[key]
fields.remove(value)
return var
data = (
{
'name' : 'morteza',
'active' : 1
},
{
'name' : 'mike',
'active' : 1
},
{
'name' : 'jessica'
},
{
'name' : 'alex',
'active' : 0
},
{
'name' : 'sarah',
'active' : 0
}
)
print random_ext.shuffle_child(data,'active',0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment