Shuffling a list of objects

后端 未结 23 1677
眼角桃花
眼角桃花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 01:09

    It works fine. I am trying it here with functions as list objects:

        from random import shuffle
    
        def foo1():
            print "foo1",
    
        def foo2():
            print "foo2",
    
        def foo3():
            print "foo3",
    
        A=[foo1,foo2,foo3]
    
        for x in A:
            x()
    
        print "\r"
    
        shuffle(A)
        for y in A:
            y()
    

    It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)

提交回复
热议问题