打乱对象列表 [英] Shuffling a list of objects
本文介绍了打乱对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象列表,我想对它们进行洗牌.我以为我可以使用 random.shuffle
方法,但是当列表是对象时,这似乎失败了.有没有改组对象的方法或其他方法?
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))
这会失败.
推荐答案
random.shuffle
应该可以工作.这是一个示例,其中对象是列表:
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
请注意,shuffle 就地有效,并返回 None.
Note that shuffle works in place, and returns None.
这篇关于打乱对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文