Shuffling a list of objects

2018-12-31 04:49发布

I have a list of objects in Python and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1,a2]

print random.shuffle(b)

This will fail.

23条回答
梦醉为红颜
2楼-- · 2018-12-31 05:24

The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.

E.g.,

ml = [[0], [1]] * 10

After,

random.shuffle(ml)

The number of [0] may be 9 or 8, but not exactly 10.

查看更多
墨雨无痕
3楼-- · 2018-12-31 05:29
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

It works fine for me. Make sure to set the random method.

查看更多
听够珍惜
4楼-- · 2018-12-31 05:35

'print func(foo)' will print the return value of 'func' when called with 'foo'. 'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing. Workaround:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

If you're more into functional programming style you might want to make the following wrapper function:

def myshuffle(ls):
    random.shuffle(ls)
    return ls
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 05:35
import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]

random.shuffle(b)
print(b)

shuffle is in place, so do not print result, which is None, but the list.

查看更多
还给你的自由
6楼-- · 2018-12-31 05:35
""" to shuffle random, set random= True """

def shuffle(x,random=False):
     shuffled = []
     ma = x
     if random == True:
         rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
         return rando
     if random == False:
          for i in range(len(ma)):
          ave = len(ma)//3
          if i < ave:
             shuffled.append(ma[i+ave])
          else:
             shuffled.append(ma[i-ave])    
     return shuffled
查看更多
登录 后发表回答