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

时间:2011-04-27 21:04:49

标签: python arrays list

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

e.g。

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

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

e.g。 '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)

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

等等。

答案 2 :(得分: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()

答案 3 :(得分: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)
]