2011-04-27 126 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) 
] 
相關問題