Shuffling a list of objects

后端 未结 23 1678
眼角桃花
眼角桃花 2020-11-22 00:29

I have a list of objects 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 the

23条回答
  •  温柔的废话
    2020-11-22 00:51

    '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
    

提交回复
热议问题