2011-04-27 87 views
2

我想要一个数组,它将有大约30件事。数组中的每一个东西都将是一组变量,并且根据数组中的哪个东西被选中,将设置不同的变量。将变量分配给列表中的随机元素? Python

例如

foo = ['fish', 'mammal', 'bird'] 
ranfoo = random.randint(0,2) 
animal = foo[ranfoo] 

这个工作得很好,从列表中返回一个随机元素,但如何则取决于所选择的项目我分配一些变量,给他们?

例如'鸟'已被随机选中,我想指定:flight = yes swim = no。或者沿着这些路线......我编程的东西有点复杂,但基本上它就是这样。我试过这个:

def thing(fish): 
    flight = no 
    swim = yes 

def thing(mammal): 
    flight = no 
    swim = yes 

def thing(bird): 
    flight = yes 
    swim = no 

foo = ['fish', 'mammal', 'bird'] 
ranfoo = random.randint(0,2) 
animal = foo[ranfoo] 

thing(animal) 

但是这也行不通,我不知道还有什么办法...帮助???

回答

5

如何制作thing班?现在

class thing: 
    def __init__(self, type = ''): 
    self.type = type 

    self.flight = (self.type in ['bird']) 
    self.swim = (self.type in ['fish', 'mammal']) 

,这是相当简单的选择一个随机的 “东西”:

import random 

things = ['fish', 'mammal', 'bird'] 
randomThing = thing(random.sample(things, 1)) 

print randomThing.type 
print randomThing.flight 
print randomThing.swim 

所以你是一个选择题的事情吗?

也许这会工作:

class Question: 
    def __init__(self, question = '', choices = [], correct = None, answer = None): 
    self.question = question 
    self.choices = choices 
    self.correct = correct 

    def answer(self, answer): 
    self.answer = answer 

    def grade(self): 
    return self.answer == self.correct 

class Test: 
    def __init__(self, questions): 
    self.questions = questions 

    def result(self): 
    return sum([question.grade() for question in self.questions]) 

    def total(self): 
    return len(self.questions) 

    def percentage(self): 
    return 100.0 * float(self.result())/float(self.total()) 

因此,一个样品测试将是这样的:

questions = [Question('What is 0 + 0?', [0, 1, 2, 3], 0), 
      Question('What is 1 + 1?', [0, 1, 2, 3], 2)] 

test = Test(questions) 

test.questions[0].answer(3) # Answers with the fourth item in answers, not three. 
test.questions[1].answer(2) 

print test.percentage() 
# Prints 50.0 
+0

但是在我编码的一个中,它不仅仅是游泳或不是游泳,它是一个随机问题的列表,有多个选择的答案......我将如何对这个不同的答案进行实现? – pythonnoobface 2011-04-27 21:32:38

+0

看到我的巨大编辑。 – Blender 2011-04-27 21:46:50

+0

@Blender这太棒了,非常感谢你!但是,我会如何让这个人选择答案呢? – pythonnoobface 2011-04-28 21:47:47

0

您需要检查是与if语句是什么动物:

if animal == 'bird': 
    flight = yes 
    swim = no 

等。

0

而是在字符串中存储的字符串,存储从一个共同的动物基地继承对象类,那么你可以这样做:

class animal: 
    def thing(self): 
      raise NotImplementedError("Should have implemented this")  

class fish(animal): 
    def thing(self): 
     """ do something with the fish """ 
     self.flight = yes 
     self.swim = no 


foo = [aFish, aMammal, aBird] 
ranfoo = random.randint(0,2) 
animal = foo[ranfoo] 
animal.thing() 
0

@ Blender的扩展的回答:

class Thing(object): 
    def __init__(self, name, flies=False, swims=False): 
     self.name = name 
     self.flies = flies 
     self.swims = swims 

foo = [ 
    Thing('fish', swims=True), 
    Thing('bat', flies=True), 
    Thing('bird', flies=True) 
] 
相关问题