【问题标题】:Ask questions with attributes and functions用属性和功能提问
【发布时间】:2020-11-26 12:27:35
【问题描述】:

这是我的代码:

class People:

    def __repr__(self):
        return f"A('{self.name}', {self.age})"

    def __init__(self, name, age):
        self.name = name
        self.age = age

def sortlist():
    people = []
    file = open('people.txt', 'r').readlines()

    for k in file:
        k = k.split()
        people.append(People(k[0], float(k[1])))
    people.sort(key=lambda c: (c.age, c.name))
    g = 0
    for g in range(len(people)):
        people[g].height = g + 1
return people

def question_height():
    for i in sortlist():
            print(random(i[0]))

def question_name():
    for i in sortlist():
        for i in range(0,104):
            print(random.choice(i.name))

代码的最后一部分(在返回人员之后)没有按照我想要的方式工作。我希望 question_height 函数从 height 属性中选择一个随机数,并且 question_name 函数从 name 属性中选择一个随机名称。

有没有人知道我可以做些什么来让它发挥作用?

【问题讨论】:

    标签: python python-3.x function random attributes


    【解决方案1】:

    只有random.choice 函数你才可以。它需要一系列项目,并随机选择其中一个。首先,您必须将People 对象列表转换为名称或高度列表。然后,只需将列表传递给random.choice 函数。

    def question_height():
        all_heights = [person.height for person in sortlist()]
        print(random.choice(all_heights))
    
    def question_name():
        all_names = [person.name for person in sortlist()]
        print(random.choice(all_names))
    

    另一种选择是将 Person 对象列表直接传递给 random.choice,然后只打印其名称或高度。

    def get_random_person(people):
        return random.choice(people)
    
    def question_height():
        people = sortlist()
        random_person = get_random_person(people)
        print(random_person.height)
        
    def question_name():
        people = sortlist()
        random_person = get_random_person(people)
        print(random_person.name)
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 2011-05-13
      • 2019-10-25
      相关资源
      最近更新 更多