将变量分配给列表中的随机元素?蟒蛇

pyt*_*ace 2 python arrays list

我想要一个阵列,里面会有大约30件事.数组中的每个东西都将是一组变量,并且根据选择数组中的哪个东西,将设置不同的变量.

例如

foo = ['fish', 'mammal', 'bird']
ranfoo = random.randint(0,2)
animal = foo[ranfoo]
Run Code Online (Sandbox Code Playgroud)

这适用于从列表中返回一个随机元素,但是,如何根据所选项目,我为它们分配一些变量?

例如'bird'已被随机选择,我想分配: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)
Run Code Online (Sandbox Code Playgroud)

但这也不起作用,我不知道还能做什么...帮助???

Ble*_*der 5

如何使一个thing班?

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

    self.flight = (self.type in ['bird'])
    self.swim = (self.type in ['fish', 'mammal'])
Run Code Online (Sandbox Code Playgroud)

现在,选择一个随机的"东西"非常简单:

import random

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

print randomThing.type
print randomThing.flight
print randomThing.swim
Run Code Online (Sandbox Code Playgroud)

所以你正在做一个多项选择的事情?

也许这会奏效:

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())
Run Code Online (Sandbox Code Playgroud)

所以样本测试将是这样的:

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
Run Code Online (Sandbox Code Playgroud)