Shuffling a list of objects

后端 未结 23 1684
眼角桃花
眼角桃花 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:55

    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.

    0 讨论(0)
  • 2020-11-22 00:59
    >>> 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.

    0 讨论(0)
  • 2020-11-22 00:59
    def shuffle(_list):
        if not _list == []:
            import random
            list2 = []
            while _list != []:
                card = random.choice(_list)
                _list.remove(card)
                list2.append(card)
            while list2 != []:
                card1 = list2[0]
                list2.remove(card1)
                _list.append(card1)
            return _list
    
    0 讨论(0)
  • 2020-11-22 01:03

    It took me some time to get that too. But the documentation for shuffle is very clear:

    shuffle list x in place; return None.

    So you shouldn't print(random.shuffle(b)). Instead do random.shuffle(b) and then print(b).

    0 讨论(0)
  • 2020-11-22 01:03
    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.

    0 讨论(0)
  • 2020-11-22 01:04

    As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using sample(a, len(a)) is the solution, using len(a) as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.

    Here's a simple version using random.sample() that returns the shuffled result as a new list.

    import random
    
    a = range(5)
    b = random.sample(a, len(a))
    print a, b, "two list same:", a == b
    # print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
    
    # The function sample allows no duplicates.
    # Result can be smaller but not larger than the input.
    a = range(555)
    b = random.sample(a, len(a))
    print "no duplicates:", a == list(set(b))
    
    try:
        random.sample(a, len(a) + 1)
    except ValueError as e:
        print "Nope!", e
    
    # print: no duplicates: True
    # print: Nope! sample larger than population
    
    0 讨论(0)
提交回复
热议问题