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

2 投票
4 回答
4949 浏览
提问于 2025-04-16 16:33

我想要一个数组,里面大约有30个东西。数组里的每个东西都是一组变量,根据选择的东西不同,变量的值也会不同。

比如:

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

这个方法可以很好地从列表中随机返回一个元素,但接下来,我该如何根据选中的项目来给这些变量赋值呢?

比如说,如果随机选中了'鸟',我想给它赋值:飞行 = 是,游泳 = 否。或者类似这样的东西……我正在编写的程序稍微复杂一点,但大致就是这样。我试过这个:

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

与其把字符串直接存储在字符串里,不如存一个继承自共同动物基类的对象。这样你就可以这样做:

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

你需要用一个if语句来检查是什么动物:

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

接下来就是这样。

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

撰写回答