To randomly mix elements in a list

Asked 2 years ago, Updated 2 years ago, 174 views

I want to mix the list that stores the objects. random.shuffle I don't know why, but None keeps returning, so I can't write it. I think it's because there's an object in the list, not a normal type like int Is there any other way to mix the list elements other than random.shuffle?

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1,a2]

print random.shuffle(b)#None

list python random shuffle

2022-09-22 22:24

1 Answers

random.shuffle can be written even if the element in the list is an object of a user-defined class. This is the case when the print is wrong.

shuffle is not the result of mixing, but None is returned print random.shuffle(b) of course prints None.

To output normally

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1,a2]

random.shuffle(b)

for i in b:
    print i.foo


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.