改组对象列表 [英] Shuffling a list of objects

查看:60
本文介绍了改组对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,我想对其进行洗牌.我以为可以使用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 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.

这篇关于改组对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆