Shuffling a list of objects

后端 未结 23 1709
眼角桃花
眼角桃花 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 01:04

    For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list) with an example:

    import random
    random.sample(list(range(10)), 10)
    

    outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]

    0 讨论(0)
  • 2020-11-22 01:05
    #!/usr/bin/python3
    
    import random
    
    s=list(range(5))
    random.shuffle(s) # << shuffle before print or assignment
    print(s)
    
    # print: [2, 4, 1, 3, 0]
    
    0 讨论(0)
  • 2020-11-22 01:07

    Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 01:12
    import random
    class a:
        foo = "bar"
    
    a1 = a()
    a2 = a()
    b = [a1.foo,a2.foo]
    random.shuffle(b)
    
    0 讨论(0)
提交回复
热议问题