Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a list of objects

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 there a method for shuffling objects 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.

like image 295
utdiscant Avatar asked Jun 10 '09 16:06

utdiscant


People also ask

How do you shuffle elements in a list?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

Can you shuffle a list in Java?

The java. util. Collections class provides shuffle() method which can be used to randomize objects stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order.

Which function is used to shuffle the list?

shuffle() function in Python. shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).


1 Answers

random.shuffle should work. Here's an example, where the objects are lists:

from random import shuffle x = [[i] for i in range(10)] shuffle(x)  # print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] # of course your results will vary 

Note that shuffle works in place, and returns None.

like image 81
tom10 Avatar answered Sep 23 '22 19:09

tom10