如何从课程中选择一个随机对象?

时间:2019-01-12 12:34:37

标签: python-3.x

我有一个100多个对象的列表,我想选择5个随机对象并将它们存储到变量中,但是我不确定该怎么做。该怎么办? 这是我的代码的简化版本:

class playableCharacters:
    def __init__(self, name, power)

        self.name = name
        self.power = power

Aatrox = playableCharacters("Aatrox", 9)

Ahri = playableCharacters("Ahri", 3)

3 个答案:

答案 0 :(得分:3)

您可以创建一个静态列表,并将对象推入__init__上的列表中,然后可以获得5个随机整数,它们可以用作该静态列表的索引。

赞:

import random

class playableCharacters:
    instances = []

    def __init__(self, name, power):
        self.name = name
        self.power = power
        __class__.instances.append(self)

Aatrox = playableCharacters("Aatrox", 9)
Ahri = playableCharacters("Ahri", 3)
# 100 more instances declaration.

randIndex = random.randrange(len(playableCharacters.instances))
randPlayerCharacter = playableCharacters.instances[randIndex]

print(randPlayerCharacter.name)

像这样,您可以再获得4个随机实例。

答案 1 :(得分:0)

您可以通过课程列表来解决

class playableCharacters:
    instances = []
    def __init__(self, name, power):

        self.name = name
        self.power = power
        __class__.instances.append(self)

a = playableCharacters("a", 9)
b = playableCharacters("b", 3)
c = playableCharacters("c", 9)
d = playableCharacters("d", 3)
# and so on.....

现在,您可以获得一组5个随机对象实例,例如

import random
random5 = random.choices(playableCharacters.instances, k=5)

如果您有成千上万个相同类的实例,我不确定这是否是最佳方法。

答案 2 :(得分:0)

您如何使用random.choices(object_list, k=n),其中n =随机项目数:

import random

class playableCharacters:
    def __init__(self, name, power):
        self.name = name
        self.power = power

    # Displays name when printed
    def __repr__(self):
        return (self.name)

# 5 Objects created
Aatrox = playableCharacters("Aatrox", 9)

Ahri = playableCharacters("Ahri", 3)

Test = playableCharacters("Test", 5)

Test2 = playableCharacters("Test2", 1)

Test3 = playableCharacters("Test3", 5)

# You could automate this, but for now here is a list of objects
myCharacters = [Aatrox, Ahri, Test, Test2, Test3]

# K=5 gives a list of 5 random
randomObjects = random.choices(myCharacters, k=5)
print(randomObjects)

编辑: 这是一个自动化版本。使用字典来表示名称和电源键/值对:

import random

class playableCharacters:
    def __init__(self, name, power):
        self.name = name
        self.power = power

    # Displays name when printed
    def __repr__(self):
        return (self.name)

objects_to_be_created = {'Aatrox':9,'Ahri':3,'Test':5,'Test2':1,'Test3':5}

myCharacters = []

# Automatation
for o in objects_to_be_created:
    x = playableCharacters(o, objects_to_be_created[o])
    myCharacters.append(x)

# K=5 gives a list of 5 random
randomObjects = random.choices(myCharacters, k=5)
print(randomObjects)